<?php

class jsonUtility{

    protected $db;
    protected $redis;
    protected $sizepage = 10;
    protected $db_prefix;

    public function __construct($mySql, $Redis)
    {

        $this->db = $mySql;
        $this->redis = $Redis;
        $this->db_prefix = \Config\Sys::$dbprefix;
    }
    # region 系统维护提示
    public function systemSystemMaintenance($cmd){
        $switchWeb = intval(self::getSystemParams("switchWeb"));
        if(!$switchWeb){
            return array(
                'cmd' => $cmd,
                'state' => 301,
                'msgid' => 404,
                'msg' => self::getSystemParams("webCloseServiceResult"),
            );
        }else{
            return array(
                'state' => 200
            );
        }
    }
    # endregion

    # region 取出所有自动发抢包用户
    public function getAutoUserList(){
        $result = $this->redisGet('games_autosend_userlist');
        if(!$result){
            $sql = "SELECT * FROM `".\Config\Sys::$dbprefix."autosend`";
            $autodata = $this->db->query($sql);
            $this->redisSet('games_autosend_userlist', $autodata);
            $result = $autodata;
        }
        return $result;
    }
    # endregion

    # region 查找某个值是否存在于多维数组中
    public function deep_in_array($value, $key, $array) {
        /*
        foreach($array as $item) {
            if(!is_array($item)) {
                if ($item == $value) {
                    return $item;
                } else {
                    continue;
                }
            }

            if(in_array($value, $item)) {
                return $item;
            } else if($this->deep_in_array($value, $item)) {
                return $item;
            }
        }
        */
        foreach($array as $item) {
            if(!is_array($item)) {
                if ($item == $value) {
                    return true;
                } else {
                    continue;
                }
            }
            /*
            if(in_array($value, $item)) {
                return $item;
            } else if($this->deep_in_array($value, $key, $item)) {
                return $item;
            }
            */
            foreach ($item as $k=>$v){
                if($key == $k && $value == $v){
                    return true;
                }else{
                    continue;
                }
            }
        }
        return false;
    }
    # endregion

    # region 取出今日、本周、上周及本月的开始和结束时间
    public function getTWLTimes($timestamp = false)
    {
        if(!$timestamp) $timestamp = time();

        # 今日的开始和结束时间
        $todayDate=date('Y-m-d', $timestamp);//今天的年月日

        $todayBegin = strtotime($todayDate);
        $todayEnd = $todayBegin + 86400 - 1;

        # 昨天的开始和结束时间
        $yesTodayBegin = $todayBegin - 86400;
        $yesTodayEnd = $todayEnd - 86400;

        # 本周开始和结束的时间戳
        $weekBegin = strtotime(date('Y-m-d', strtotime("this week Monday", $timestamp)));
        $weekEnd = strtotime(date('Y-m-d', strtotime("this week Sunday", $timestamp))) + 24 * 3600 - 1;

        # 上周开始和结束的时间戳
        $lastWeekBegin = strtotime(date('Y-m-d', strtotime("last week Monday", $timestamp)));
        $lastWeekEnd = strtotime(date('Y-m-d', strtotime("last week Sunday", $timestamp))) + 24 * 3600 - 1;

        # 本月开始和结束的时间戳
        $monthBegin = mktime(0,0,0,date('m'),1,date('Y'));
        $monthEnd = mktime(23,59,59,date('m'),date('t'),date('Y'));

        return array(
            'todayBegin' => $todayBegin,
            'todayEnd' => $todayEnd,
            'yesTodayBegin' => $yesTodayBegin,
            'yesTodayEnd' => $yesTodayEnd,
            'weekBegin' => $weekBegin,
            'weekEnd' => $weekEnd,
            'lastWeekBegin' => $lastWeekBegin,
            'lastWeekEnd' => $lastWeekEnd,
            'monthBegin' => $monthBegin,
            'monthEnd' => $monthEnd,
        );
    }
    # endregion

    # region 验证邮箱
    # 验证邮箱
    public function isEmail($string)
    {
        $pattern = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";
        return (preg_match( $pattern, $string) ? true : false );
    }
    # endregion

    # region 验证手机号码
    public function isMobileNumber($mobile)
    {
        return (preg_match("/^1[34578]\d{9}$/", $mobile) ? true : false);
    }
    # endregion

    # region 验证银行卡
    /**
     * @param $s string 16-19 位卡号
     */
    /*
  16-19 位卡号校验位采用 Luhm 校验方法计算：
    1，将未带校验位的 15 位卡号从右依次编号 1 到 15，位于奇数位号上的数字乘以 2
    2，将奇位乘积的个十位全部相加，再加上所有偶数位上的数字
    3，将加法和加上校验位能被 10 整除。
*/
    public function isBankNumber($s)
    {
        $n = 0;
        for ($i = strlen($s); $i >= 1; $i--) {
            $index=$i-1;
            //偶数位
            if ($i % 2==0) {
                $n += $s{$index};
            } else {//奇数位
                $t = $s{$index} * 2;
                if ($t > 9) {
                    $t = (int)($t/10)+ $t%10;
                }
                $n += $t;
            }
        }
        return ($n % 10) == 0;
    }
    # endregion

    # region 在二维数组中查找指定$key并返回指定$resultKey的值
    /**
     * 在二维数组中查找指定$key并返回指定$resultKey的值
     * @param $arr  二维数组
     * @param $key  要查找的数组列
     * @param $value 查找的列的值
     * @param $resultKey 要返回数组中的列名
     * @return int
     */
    public function getOddsWinSort($arr, $key, $value, $resultKey)
    {
        $result = 0;
        foreach($arr as $keyp=>$valuep){
            if($valuep[$key]==$value){
                $result = $valuep[$resultKey];
            }
        }
        return $result;
    }
    # endregion

    # region 检测红包是否有出现指定的尾数，如果没有即重新生成
    /**
     * 检测红包是否有出现指定的尾数，如果没有即重新生成
     * @param $roundRedPackets array 已生成好的红包数据
     * @param $mantissa string|int 指定要出现的尾数
     */
    public function existsShowMantissa($roundRedPackets, $mantissa)
    {
        $isShow = false;
        foreach ($roundRedPackets as $v)
        {
            $current_mantissa = substr($v['coin'], -1);   //小数点后二位
            if($current_mantissa == $mantissa){
                $isShow = true;
                break;
            }
        }
        return $isShow;
    }
    # endregion

    # region 二维数组根据$sortKey字段排序
    /**
     * 二维数组根据$sortKey字段排序
     * @param $arr 要排序的二维数组
     * @param $sortKey 排序字段
     * @param string $direction 排序方向（DESC 降序；ASC 升序）
     * @return array
     */
    public function sortArray($arr, $sortKey, $direction = "ASC")
    {
        $arrSort = array();
        foreach($arr AS $uniqid => $row){
            foreach($row AS $key=>$value){
                $arrSort[$key][$uniqid] = $value;
            }
        }
        array_multisort($arrSort[$sortKey], constant("SORT_".$direction), $arr);
        return $arr;
    }
    # endregion

    # region 二维数组随机排序
    public function shuffle_assoc($list) {
        if (!is_array($list)) return $list;

        $keys = array_keys($list);
        shuffle($keys);
        $random = array();
        foreach ($keys as $key)
            $random[$key] = $this->shuffle_assoc($list[$key]);
        return $random;
    }
    # endregion

    # region 去掉房间及游戏标识前缀（game,chat）

    /**
     * 去掉房间及游戏标识前缀（game,chat）
     * @param $string
     * @return mixed
     */
    public function getGameOrChatID($string)
    {
        $string = str_replace('chat_','',$string);
        $string = str_replace('game_','',$string);
        return $string;
    }
    # endregion

    # region 格式化金币为两位小数
    /**
     * 格式化金币为两位小数
     * @param $coin
     * @return string
     */
    public function formatCoin($coin)
    {
        return number_format($coin, 2, '.', '');
    }
    # endregion

    # region 检测字符串中包含大小写字符的个数
    /*
     * 检测字符串中包含大小写字符的个数
     * @param string $strings 要检测的字符串
     * @param array $result 返回检测结果数组（0=>大写个数,1=>小写个数）
     */
    public function up_low_sizeof($strings = ''){
        $result = array(0=>0,1=>0);
        if(!empty($strings)){
            preg_match_all('#(?<up>[A-Z]{1})#',$strings,$a);
            $result[0] = sizeof($a['up']); //大写字母个数
            preg_match_all('#(?<low>[a-z]{1})#',$strings,$a);
            $result[1] = sizeof($a['low']); //小写字母个数
        }
        return $result;
    }
    # endregion

    # region 生成随机长度的数字、字母组合
    /**
     * 生成随机长度的数字、字母组合
     * 函数encrypt($string,$operation,$key)
     * @param string $string 需要加密解密的字符串
     * @param string $operation 判断是加密还是解密，E表示加密，D表示解密；
     * @param string $key 密匙。
     */
    public function randString($length=4){
        // 密码字符集，可任意添加你需要的字符
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $password = '';
        for ( $i = 0; $i < $length; $i++ )
        {
            // 这里提供两种字符获取方式
            // 第一种是使用 substr 截取$chars中的任意一位字符；
            // 第二种是取字符数组 $chars 的任意元素
            // $password .= substr($chars, mt_rand(0, strlen($chars) – 1), 1);
            $password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
        }
        return $password;
    }
    # endregion

    # region 加密解密字符串
    /**
     * 加密解密字符串
     * @param $string 要加密（解密）的字符串
     * @param $operation 操作符 - E：加密，D：解密
     * @param string $key 密码串
     * @return bool|mixed|string
     */
    public function encrypt($string,$operation,$key=''){
        $key=md5($key);
        $key_length=strlen($key);
        $string=$operation=='D'?base64_decode($string):substr(md5($string.$key),0,8).$string;
        $string_length=strlen($string);
        $rndkey=$box=array();
        $result='';
        for($i=0;$i<=255;$i++){
            $rndkey[$i]=ord($key[$i%$key_length]);
            $box[$i]=$i;
        }
        for($j=$i=0;$i<256;$i++){
            $j=($j+$box[$i]+$rndkey[$i])%256;
            $tmp=$box[$i];
            $box[$i]=$box[$j];
            $box[$j]=$tmp;
        }
        for($a=$j=$i=0;$i<$string_length;$i++){
            $a=($a+1)%256;
            $j=($j+$box[$a])%256;
            $tmp=$box[$a];
            $box[$a]=$box[$j];
            $box[$j]=$tmp;
            $result.=chr(ord($string[$i])^($box[($box[$a]+$box[$j])%256]));
        }
        if($operation=='D'){
            if(substr($result,0,8)==substr(md5(substr($result,8).$key),0,8)){
                return substr($result,8);
            }else{
                return '';
            }
        }else{
            return str_replace('=','',base64_encode($result));
        }
    }
    # endregion

    #region 过滤及验证参数

    /**
     * 过滤及验证参数
     * @param $key
     * @param $arr
     * @param string $dataType
     * @param int $default
     * @return false|float|int|string
     */
    public function existsKey($key,$arr,$dataType='N',$default=0)
    {
        $result = '';
        if(is_array($arr) && count($arr)>0 && array_key_exists($key,$arr)){
            switch($dataType){
                case 'N':
                    $result = intval($arr[$key]);
                    break;
                case "S": //字符型
                    $result = strval($arr[$key]);
                    break;
                case 'D': //日期型 2017-10-11
                    $result = date('Y-m-d',strtotime($arr[$key]));
                    break;
                case 'F': //货币数字
                    $result = floatval($arr[$key]);
                    break;
            }
        }else{
            switch($dataType){
                case 'N':
                    $result = $default ? $default : 0;
                    break;
                case "S": //字符型
                    $result = $default ? $default : '';
                    break;
                case 'D': //日期型 2017-10-11
                    $result = $default ? $default : '';
                    break;
                case 'F': //货币数字
                    $result = $default ? $default : 0;
                    break;
            }
        }
        return $result;
    }
    # endregion

    # region 生成唯一订单号
    public function neworderno(){
        $beginStr = chr(mt_rand(65, 90));//大写字母
        $orderSn = $beginStr . date('Y') . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        return $orderSn;
    }
    # endregion

    # region 格式化时间截
    /**
     * 格式化时间截 - 聊天时间展示
     * @param $times int 时间截
     * @return false|string
     */
    public function formatTimes($times)
    {
        $w_begin = mktime(0, 0 , 0,date("m"),date("d")-date("w")+1,date("Y"));
        $w_end = mktime(0, 0 , 0,date("m"),date("d")-date("w")+7,date("Y"));

        $wu_begin = mktime(0,0,0,date('m'),date('d')-date('w')+1-7,date('Y'));
        $wu_end = mktime(0,0,0,date('m'),date('d')-date('w')+7-7+1,date('Y'));

        $result = date('Y-m-d- H:i:s', (int)$times);
        $limit = time() - $times;

        $day_begin = strtotime(date('Y-m-d',time()));
        $day_end = $day_begin + 24 * 3600;

        if($day_begin < $times && $day_end > $times){
            $result = date('H:i:s', (int)$times);
        }elseif(($day_begin - 86400) < $times && ($day_end - 86400) > $times){
            //昨天
            $result = '昨天 '.date('H:i:s', (int)$times);
        }elseif(($day_begin - 86400 - 86400) < $times && ($day_end - 86400 -86400) > $times){
            //前天
            $result = '前天 '.date('H:i:s', (int)$times);
        }elseif($times > $w_begin && $times < $w_end){
            //本周
            $w = "星期" . mb_substr( "日一二三四五六",date("w", $times),1,"utf-8" );
            $result = $w.' '.date('H:i:s', (int)$times);
        }elseif ($times > $wu_begin && $times < $wu_end){
            //上周
            $w = "上周" . mb_substr( "日一二三四五六",date("w", $times),1,"utf-8" );
            $result = $w.' '.date('H:i:s', (int)$times);
        }else{
            $result = date('Y-m-d H:i:s', (int)$times);
        }
        return $result;
    }
    # endregion

    # region 随机抽取红包金额
    public function randArrayCoin($arr){
        $result = array(
            'coin' => 0,
            'redpackets' => array(),
            'key' =>0,
        );
        if(count($arr)>=1) {
            $key = array_rand($arr, 1);
            $value = $arr[$key]['coin'];
            $result = array(
                'coin' => $value,
                'redpackets' => $arr,
                'key' => $key,
            );
        }
        return $result;
    }
    # endregion

    # region 红包算法，金额参数以分为单位
    /**
     * @param $totalAmount 总金额
     * @param $totalPeopleNum 总包数
     * @return array 分配好的红包金额
     */
    public function divideRedPackage($totalAmount,$totalPeopleNum){
        $amountList = array();
        $restAmount = $totalAmount;
        $restPeopleNum = $totalPeopleNum;
        $minvalue = 0.15;
        for ($i = 0; $i < $totalPeopleNum - 1; $i++) {
            mt_srand(time());
            // 随机范围：[1，剩余人均金额的两倍)，左闭右开
            $amount = mt_rand($minvalue * 100, (($restAmount / $restPeopleNum *2 -1) + 1) * 100) / 100;
            $restAmount -= $amount;
            $restPeopleNum--;
            $amountList[$i] = $amount;
        }
        $amountList[$totalPeopleNum - 1] = $restAmount;
        return $amountList;
    }
    # endregion

    # region 红包算法
    /**
     * 红包算法
     * @param float $total 红包总金额
     * @param int $num 需要分配的个数
     */
    public function redPacketRound($total,$num=5,$mantissa=0){
        //$total=10;//红包总额
        //$num=8;// 分成8个红包，支持8人随机领取
        $old_total = $total;
        mt_srand(time());
        $min = ($total / $num / 2) / 100;//每个人最少能收到的金额
        //if(intval($mantissa)>0) $minrand =  ($mantissa / 100);
        //if(intval($mantissa)==0) $minrand = mt_rand(1,9) / 100;
        //$min += $minrand;
        if($min < 0.01) $min = 0.01;
        $datas = array();
        for ($i=1;$i<$num;$i++)
        {
            $safe_eg = (float)($num-$i);
            // $safe_total=((float)$total - ($num-$i) * $min-$minrand) / (float)($safe_eg);//随机安全上限
            $safe_total=((float)$total - ($num-$i) * $min) / (float)($safe_eg);//随机安全上限
            $money = random_int($min*100,$safe_total*100)/100;
            $total=$total-$money;
            $datas[$i] = array(
                'coin' => $this->formatCoin($money, 2),
            );
        }
        $datas[$num] = array(
            'coin' => $this->formatCoin($total),
        );
        shuffle($datas);
        //$key = array_rand($datas);
        //print_r('第'.($i).'个红包：'.$total.' 元，余额：'.$total.' 元 '."\n");
        return $datas;
    }
    # endregion

    # region 随机分配红包金额
    /**
     * 随机抽取数组中的一行数据，并删除当前数组行后返回被抽取到的数值及重新组合后的数据
     * @param $arr array 需要处理的数组
     * @return array
     */
    public function getRedPacketFromArray($arr, $args=array('usertype'=>0))
    {
        $result = array(
            'coin' => 0,
            'redpackets' => array(),
        );
        //print_r($arr);
        if(count($arr)>=1) {
            $tryarr = $this->randArrayCoin($arr);
            $isreplay = true;
            $autoUserList = $this->getAutoUserList();
            $replay = 0;
            $replayend = 5; # 总共计算5次，5次后不再重复
            # 只有正式用户才进行概率分配计算
            if(isset($args['usertype']) && $args['usertype']==1) {
                switch ($args['gameid']) {
                    case 1:
                        # 测试是机器人还是玩家，有几个玩家及几个机器人
                        break;
                    case 2:
                        break;
                    case 3:
                        # 先检测有没有出雷
                        # 如果有出雷，在机器人那里尽量不出现
                        # 如果有出多个雷，玩家一定要分配到一个
                        while ($isreplay) {
                            //echo $replay . '=》';
                            $isreplay = false;
                            $coin = strval($this->formatCoin($tryarr['coin']));
                            $current_mantissa = substr($coin, -1);   //小数点后二位
                            if ($this->deep_in_array($args['uid'], 'uid', $autoUserList)) {
                                if ($current_mantissa == $args['mantissa']) {
                                    $tryarr = $this->randArrayCoin($arr);
                                    $isreplay = true;
                                    if ($replay >= $replayend) {
                                        $isreplay = false;
                                    }
                                    //echo 'COIN='.$tryarr['coin'].'\r\n';
                                }
                            }
                            $replay++;
                        }
                        break;
                    case 4:
                        break;
                    case 5:
                        /*
                        $coin = strval(number_format($arr['coin'], 2, '.', ''));
                        $n1 = substr($coin,-2,1); //小数点第一位
                        $n2 = substr($coin,-1);   //小数点后二位

                        $winsort_odds_key = 'n'.(($n1+$n2) % 10); // 牛几

                        // 最后是最大的牌型：牛牛
                        if((($n1+$n2) % 10)==0){
                            $winsort_odds_key = "n0";
                        }
                        */
                        break;
                }
            }
            # 删除当前的红包金额
            unset($arr[$tryarr['key']]);
            $result = array(
                'coin' => $tryarr['coin'],
                'redpackets' => $arr,
            );
        }
        return $result;
    }
    # endregion

    # region 替换字符串为系统设置的值
    /**
     * 字符串参数规则
     * @param $string
     * @return mixed
     */
    public function replaceKeys($string){
        $currency_unit = $this->getSystemParams('currencyName');
        $website_name = $this->getSystemParams('website_name');
        $webimgsurl = $this->getSystemParams('webimgsurl');
        $string = str_replace('{currency_unit}',$currency_unit, $string);
        $string = str_replace('{website_name}',$website_name, $string);
        $string = str_replace('{webimgsurl}',$webimgsurl, $string);
        return $string;
    }
    # endregion

    # region 取指定$token用户的余额
    /**
     * 取指定$token用户的余额
     * 原函数名：getUserCoin 还没有确定在哪个过程有调用(2018-05-15 12:07:43)
     */
    public function getUserCoinForToken($token)
    {
        $sql = "SELECT `coin` FROM `".\Config\Sys::$dbprefix."users` WHERE `isdelete`=0 AND `webtoken`='{$token}'";
        $data = $this->db->column($sql);
        $result = $data[0];
        if(empty($result)) $result = 0;
        return $result;
    }
    # endregion

    # region 取系统参数及设置等
    public function getSystemParams($keyname)
    {
        $redis_key = Config\Sys::$redisKey['SPAMS'].$keyname;
        $data = $this->redisGet($redis_key);
        if(!$data)
        {
            $sql = "SELECT `value` FROM `{$this->db_prefix}params` WHERE `name`='{$keyname}' LIMIT 1";
            $data = $this->db->row($sql);
            if($data) {
                $data = $data['value'];
                $this->redisSet($redis_key, $data);
            }
        }
        return $data;
    }
    # endregion

    #region 设置注册和登录时返回给用户的系统设置参数
    public function getForClientParams(){
        return array(
            'currencyName' => $this->getSystemParams('currencyName'),
            'enablecash' => $this->getSystemParams('enablecash'),
            'enablerecharge' => $this->getSystemParams('enablerecharge'),
            'iosaudit' => $this->getSystemParams('iosaudit'),
            'version' => $this->getSystemParams('version'),
            'appupdateurl' => $this->getSystemParams('appupdateurl'),
            'imgsurl' => $this->getSystemParams('imgsurl'),
            'apiurl' => $this->getSystemParams('apiurl'),
            'apkdownloadurl' => $this->getSystemParams('apkdownloadurl'),
            'iosdownloadurl' => $this->getSystemParams('iosdownloadurl'),
            'weburl' => $this->getSystemParams('weburl'),
            'registerurl' => $this->getSystemParams('registerurl'),
            'homeservice' => $this->getSystemParams('homeservice'),
            'online'    =>  $this->getSystemParams('onlinecount'),
            'wssurl'    => $this->getSystemParams('wssurl'),
            'homerolling'    => $this->getSystemParams('homerolling'),
            'homenotice'    => $this->getSystemParams('homenotice'),
        );
    }
    # endregion

    # region 系统在线人数
    /**
     * 系统在线人数
     * @return int
     */
    public function getUserOnline()
    {
        $redis_key = Config\Sys::$redisKey['SOSUM'];
        $data = $this->redisGet($redis_key);
        if(!$data)
        {
            $data = 1;
        }
        return $data;
    }
    # endregion

    # region 玩家的未读信息
    public function getUserMailCount($uid)
    {
        # 找出七天内没有拉取的数据
        $nowtime = date('Y-m-d',time());
        $endtime = strtotime($nowtime) + 86400;
        $begintime = strtotime($nowtime) - (86400 * 7);
        $sql = "select `id` FROM ".\Config\Sys::$dbprefix."mailbox  WHERE `touid`=0 AND `status`=0 AND `actiontime` BETWEEN ".$begintime." AND ".$endtime;
        $datas = $this->db->query($sql);
        $tablename = \Config\Sys::$dbprefix.'mailbox_user';
//        foreach ($datas as $v)
//        {
//            $update_sql = 'INSERT INTO `'.$tablename.'` (`forid`,`uid`) VALUES('.$v['id'].','.$uid.') ON DUPLICATE KEY UPDATE forid='.$v['id'];
//            $this->db->query($update_sql);
//        }
        //$fields = "l.`id`,l.`title`,l.`actiontime`,u.*";
        $fields = "COUNT(uid) AS __TOTAL";
        $where = "`status`=0 AND uid=" . $uid;
        $tablename = \Config\Sys::$dbprefix . 'mailbox_user';
        $sql = "SELECT {$fields} FROM {$tablename} WHERE {$where}";
        $total = $this->db->row($sql);
        $total = $total['__TOTAL'];
        return $total;
    }
    # endregion

    # region 生成用户号码
    public function makeUserNo()
    {
        $min_rand = 10000;
        $max_rand = 99999999;
        $uno = mt_rand($min_rand, $max_rand);
        $data = $this->db->query("SELECT `uid` FROM `".\Config\Sys::$dbprefix."users` WHERE `uno`='{$uno}' LIMIT 1");
        if($data)
        {
            $this->makeUserNo();
        }else{
            return $uno;
        }
    }
    # endregion

    # region 用户离下次VIP升级的相关数据
    public function userNextUpdateLevel($uid, $lid, $rechargecoin, $betcoin){
        # 缓存1分钟
        $redisKeyName = 'game_user_rbnxt_'.$uid;

        //$result = $this->redisGet($redisKeyName);
        //if(!$result) {
        //$sql = 'SELECT IFNULL(SUM(`rechargeamount`),0) AS _TOTAL FROM `' . \Config\Sys::$dbprefix . 'users_recharge` WHERE `uid`=' . $uid . ' AND `state`=1';
        //$recharge = $this->db->row($sql);

        //$sql = 'SELECT IFNULL(SUM(`betcoin`),0) AS _TOTAL FROM `' . \Config\Sys::$dbprefix . 'betslog` WHERE `uid`=' . $uid . ' AND `state`=1';
        //$bet = $this->db->row($sql);

        $sql = 'SELECT `lid`,`rechargesum`,`cointotal` FROM `' . \Config\Sys::$dbprefix . 'userlevel` WHERE `lid`>' . $lid . ' ORDER BY `lid` ASC LIMIT 1';
        $level = $this->db->row($sql);

        $nextRecharge = $level['rechargesum'] - $rechargecoin;
        $nextBet = $level['cointotal'] - $betcoin;

        $result = array(
            'recharge' => $rechargecoin,
            'betcoin' => $betcoin,
            'nextLid' => $level['lid'],
            'nextRecharge' => $this->formatCoin($nextRecharge),
            'nextBet' => $this->formatCoin($nextBet),
        );

        //$this->redisSetEx($redisKeyName, $result, 120);
        //}
        return $result;
    }
    # endregion

    # region 生成用户的token
    /**
     * 生成用户的token
     * @param $uno
     * @param $keys
     * @return string
     */
    public function settoken($uno, $keys)
    {
        $str = md5($uno.(uniqid(md5(microtime(true)),true)).$keys);  //生成一个不会重复的字符串
        $str = sha1($str);  //加密
        return $str;
    }
    # endregion

    # region 跑马灯内容
    public function getMarquees($paras)
    {

        //需要处理的页面参数，用来翻页操作及生成缓存键
        $url_args = array(
            'cmd',
            'gameid|N|0',
            'remoteip',
        );
        $paras = $this->get_url_args($paras, $url_args);

        $pagesize = 10; //取十行内容
        $redisKey = \Config\Sys::$redisKey['MARQUEE'].$paras['gameid'];

        $datas = $this->redisGet($redisKey);

        if(!$datas){
            $fields = "(SELECT u.nickname FROM rp_users u WHERE u.uid=l.uid) AS nickname,
                        (SELECT u.avatar FROM rp_users u WHERE u.uid=l.uid) AS avatar,
                        (SELECT g.title FROM rp_games g WHERE g.id=l.gameid) AS title,
                        l.profit,
                        (SELECT o.cardtitle FROM rp_games_odds o WHERE o.gameid=l.gameid AND o.cardtype=l.cardtype) AS cardtitle";
            $where = 'l.state = 1  AND l.profit > 0';
            if (!empty($paras['gameid'])) $where .= ' AND l.`gameid`=' . $paras['gameid'];

            $sql = "SELECT ".$fields." FROM ".\Config\Sys::$dbprefix."betslog l WHERE ".$where." ORDER BY l.times DESC LIMIT ".$pagesize;
            $datas = $this->db->query($sql);
            foreach ($datas as $k=>$v){
                switch ($v['cardtitle'])
                {
                    case '2倍':
                    case '1.5倍':
                    case '1倍':
                    case '比大小':
                        $datas[$k]['cardtitle'] = '';
                        break;
                    default:
                        break;
                }
            }
            $this->redisSetEx($redisKey, $datas, 1800);
        }
        return array(
            'state' => 200,
            'cmd' => $paras['cmd'],
            'gameid' => $paras['gameid'],
            'datas' => $datas,
        );
    }
    # endregion

    # region 验证用户的token并拉取用户的相关数据
    /**
     * 验证token的有效性
     * @param $token
     * @return mixed
     */
    public function exitsToKen($token,$cmd)
    {

        $userResult['cmd'] = $cmd;


        $sysMt = self::systemSystemMaintenance($cmd);
        if($sysMt['state'] != 200){
            return $sysMt;
        }

        if(empty($token)){
            $user = false;
        }else {
            $field = "`uid`,`parentid`,`uno`,`username`,`regtimes`,`lastlogintimes`,`coin`,`nickname`,`recharge`,`avatar`,`usertype`,`tel`,`qq`,`wx`,`userlevel`,`agentlevel`,`score`,`backtotal`,`betcoin`,`rebate`";
            $where = "`isdelete`=0 AND `webtoken`='{$token}'";
            $sql = "SELECT {$field} FROM `{$this->db_prefix}users` WHERE {$where} LIMIT 1";
            $user = $this->db->row($sql);
        }

        $lastlogintimes = intval($user['lastlogintimes']) + 60 * 60 * 24; //30分钟没有活动即退出
        $nowtime = time();
        $userResult['cmd'] = $cmd;
        $userResult['state'] = 200;
        $userResult['usercoin'] = 0;
        if (!$user) {
            //print_r('没用找到用户');
            //登录的token失效，要重新登录了
            $userResult['state'] = 301;
            $userResult['msgid'] = 10002;
            return $userResult;
        }
        if ($lastlogintimes < $nowtime) {
            //print_r('登录超时');
            //登录失效，要重新登录了
            $userResult['state'] = 301;
            $userResult['msgid'] = 10001;
            return $userResult;
        }
        if ($userResult['state'] == 200) {
            $userResult['uid'] = $user['uid'];
            $userResult['uno'] = $user['uno'];
            $userResult['usercoin'] = $user['coin'];
            $userResult['givecoin'] = 0;
            $userResult['reggivecoin'] = 0;
            $userResult['regdisablegivecoin'] = 0;
            $userResult['username'] = $user['username'];
            $userResult['nickname'] = $user['nickname'];
            $userResult['avatar'] = $user['avatar'];
            $userResult['tel'] = (empty($user['tel']) ? '' : (substr($user['tel'],0,3).'****'.substr($user['tel'],-1,4)));//$user['tel'];
            $userResult['qq'] = (empty($user['qq']) ? '' : (substr($user['qq'],0,3).'****'.substr($user['qq'],-1,4)));//$user['qq'];
            $userResult['wx'] = (empty($user['wx']) ? '' : (substr($user['wx'],0,2).'****'.substr($user['wx'],-1,2)));//$user['wx'];
            $userResult['userscore'] = $user['score'];
            $userResult['recharge'] = $user['recharge'];
            $userResult['betcoin'] = $user['betcoin'];
            $userResult['backtotal'] = $user['backtotal'];
            $userResult['usertype'] = $user['usertype'];
            $userResult['userlevel'] = $user['userlevel'];
            $userResult['agentlevel'] = $user['agentlevel'];
            $userResult['parentid'] = $user['parentid'];
            $userResult['rebate'] = $user['rebate'];
            $userResult['regtimes'] = $user['regtimes'];
            $userResult['token'] = $token;
            //$userResult['online'];
            //更新token的有效时间
            //print_r('是否超1740了：'.($nowtime - intval($user['lastlogintimes'])));
            if($nowtime - intval($user['lastlogintimes']) >= 1740) {
                //print_r('超过1740了更新下时间');
                $this->db->update(\Config\Sys::$dbprefix . 'users')->cols(
                    array(
                        'lastlogintimes' => $nowtime,
                        'lastip' => isset($_SESSION['remoteip']) ? $_SESSION['remoteip'] : 0,
                    )
                )->where("webtoken='" . $token . "'")->query();
            }
        }else{
            //登录的token失效，要重新登录了
            $userResult = array(
                'state' => 301,
                'msgid' => 10002,
            );
        }
        return $userResult;
    }
    # endregion

    # region 取出列表用户的余额数据并按用户的推送给玩家
    /**
     * 取出列表用户的余额数据并按用户的推送给玩家，
     * @param $users 需要推送的用户列表
     */
    public function sendToUidFreeCoinForIssue($users)
    {
        //取出列表用户的余额数据并推送
        $ids = "0";
        foreach($users as $key=>$val)
        {
            $ids .= "," . $val['uid'];
        }
        $sql = "select `uno`,`coin`,`score` from `".\Config\Sys::$dbprefix."users` where `uid` in({$ids})";
        $datas = $this->db->query($sql);
        $coins = array();
        foreach($datas as $key=>$val)
        {
            $coins[$val['uno']] = array(
                'coin' => $val['coin'],
                'score' => $val['score'],
            );
        }
        return $coins;
    }
    # endregion

    # region 取出用户的赠送金额
    /*
     * 2018-08-02
     * 由于采用了月分表，本过程无法直接能用了
     */
    public function getUserRechargeAndGive($uid){
        # 14 -> 收到玩家传来红包,
        # 21 -> 充值,
        # 23 -> 注册赠送,
        $liqtype = '14,21,23';
        $fields = 'IFNULL(sum(betcoin),0) AS betcoin,(SELECT IFNULL(SUM(`coin`),0) from `'.\Config\Sys::$dbprefix.'coinlog` where uid='.$uid.' AND (liqtype IN('.$liqtype.'))) AS givetotal';
        $where = 'uid=' . $uid . ' AND state=1';
        $tablename = \Config\Sys::$dbprefix . 'betslog';

        $sql = "SELECT {$fields} from {$tablename} where {$where}";
        $data = $this->db->row($sql);
        $coinodds = $this->getSystemParams('coinodds');
        $minbetcoin = $data['givetotal'] * $coinodds;
        $result = array(
            'state' => 303,
            'msgid' => 10073,
            'coin' => $this->formatCoin($minbetcoin - $data['betcoin']),
            'cmd'=> 'cash',
        );
        # 如果流水足即可以转帐或提现
        if($data['betcoin'] >= $minbetcoin)
        {
            $result = array(
                'state' => 200,
            );
        }
        # 检测接收方是不是自己的直属，如果是直属不限制

        return $result;
    }
    # endregion

    # region 代理等级列表
    /**
     * @return upagentnumbers int 首次成为代理的有效人数
     * @return agent array 代理等级列表
     */
    public function getAgentLevelList()
    {
        $redis_key = \Config\Sys::$redisKey['UAGENT'].'list';
        $result = $this->redisGet($redis_key);
        if(!$result){
            $db_prefix = \Config\Sys::$dbprefix;
            $result['upagentnumbers'] = intval($this->getSystemParams('upagentnumbers'));
            $sql = "SELECT * FROM `{$db_prefix}agentlevel` WHERE `title`<>'内部' ORDER BY `lid` ASC";
            $agent = $this->db->query($sql);
            $result['agent'] = $agent;
            $result['agentupdategiveway'] = intval($this->getSystemParams('agentupdategiveway'));
            $this->redisSet($redis_key, $result);
        }
        return $result;
    }
    # endregion

    # region 单个代理等级数据
    public function getAgentLevelForLid($paras)
    {
        //需要处理的页面参数，用来翻页操作及生成缓存键
        $url_args = array(
            'lid',
        );
        $paras = $this->get_url_args($paras, $url_args);
        if($paras['lid']==''){
            return array(
                'state' => 404,
                'msgid' => 10000,
            );
        }

        $redis_key = \Config\Sys::$redisKey['UAGENT'].$paras['lid'];
        $result = $this->redisGet($redis_key);
        if(!$result){
            $db_prefix = \Config\Sys::$dbprefix;
            $sql = "SELECT * FROM `{$db_prefix}agentlevel` WHERE `lid`={$paras['lid']} ORDER BY `lid` ASC";
            $result = $this->db->row($sql);
            $this->redisSet($redis_key, $result);
        }
        return $result;
    }
    # endregion

    # region 代理等级中查找指定的lid等级的下一级数组
    /**
     * @param $nextlid int 当前代理等级的 lid
     * @param bool $getall
     * @return bool & array false 或 代理数据行
     */
    public function getAgentLevelForRedis($lid,$getall = true){
        $result = false;
        $agents = $this->getAgentLevelList();
        if(!$getall){
            foreach ($agents['agent'] as $k=>$v) {
                if (intval($v['lid']) > intval($lid)) {
                    $result = $v;
                    break;
                }
            }
        }else{
            $result = $agents['agent'];
        }
        return $result;
    }
    # endregion

    # region 用户等级列表
    public function getUserLevelList()
    {
        $redis_key = \Config\Sys::$redisKey['ULEVEL'].'list';
        $result = $this->redisGet($redis_key);
        if(!$result){
            $db_prefix = \Config\Sys::$dbprefix;
            $sql = "SELECT * FROM `{$db_prefix}userlevel` ORDER BY `lid` ASC";
            $level = $this->db->query($sql);
            $result['level'] = $level;
            $this->redisSet($redis_key, $result);
        }
        return $result;
    }
    # endregion

    # region 单个用户等级数据
    public function getUserLevelForLid($paras)
    {
        //需要处理的页面参数，用来翻页操作及生成缓存键
        $url_args = array(
            'lid',
        );
        $paras = $this->get_url_args($paras, $url_args);
        if($paras['lid']==''){
            return array(
                'state' => 404,
                'msgid' => 10000,
            );
        }

        $redis_key = \Config\Sys::$redisKey['ULEVEL'].$paras['lid'];

        $result = $this->redisGet($redis_key);

        if(!$result){
            $db_prefix = \Config\Sys::$dbprefix;
            $sql = "SELECT * FROM `{$db_prefix}agentlevel` WHERE `lid`={$paras['lid']} ORDER BY `lid` ASC";
            $result = $this->db->row($sql);
            $this->redisSet($redis_key, $result);
        }
        return $result;
    }
    # endregion

    # region 已完成的指定期数红包
    /**
     * 已完成的指定期数红包
     * @param $redis
     * @param $db
     * @param $issue
     * @return mixed
     */
    public function getGameForIssueIsEnd($issue)
    {
        $redis_key = \Config\Sys::$redisKey['GOISSUE'].$issue;
//        $data = $this->redisGet($redis_key);
//        if(!$data){
        $autosql = "SELECT b.`id`,u.`uno`,b.`issue`,b.`gameid`,(SELECT o.`cardtitle` FROM `".\Config\Sys::$dbprefix."games_odds` o WHERE o.cardtype=b.`cardtype` AND o.`gameid`=b.`gameid` LIMIT 1) AS cardtitle,b.`odds`,b.`mantissa`,b.`coin`,b.`times`,b.`betcoin`,b.`ticket`,b.`winerprofit`,b.`profit`,u.`uid` AS userid,u.`nickname`,u.`avatar` ";
        $autosql .="FROM `".\Config\Sys::$dbprefix."autobetslog` b,`".\Config\Sys::$dbprefix."users` u WHERE u.`uid`=b.`uid` AND b.`issue`='{$issue}' ORDER BY `times` ASC";

        $sql = "SELECT b.`id`,u.`uno`,b.`issue`,b.`gameid`,(SELECT o.`cardtitle` FROM `".\Config\Sys::$dbprefix."games_odds` o WHERE o.cardtype=b.`cardtype` AND o.`gameid`=b.`gameid` LIMIT 1) AS cardtitle,b.`odds`,b.`mantissa`,b.`coin`,b.`times`,b.`betcoin`,b.`ticket`,b.`winerprofit`,b.`profit`,u.`uid` AS userid,u.`nickname`,u.`avatar` ";
        $sql .="FROM `".\Config\Sys::$dbprefix."betslog` b,`".\Config\Sys::$dbprefix."users` u WHERE u.`uid`=b.`uid` AND b.`issue`='{$issue}' UNION {$autosql}";

        //print_r($sql);
        $data['grabusers'] = $this->db->query($sql);

        $sql = "SELECT * FROM `".\Config\Sys::$dbprefix."bets` WHERE `issue`='{$issue}'";
        //print_r($sql);
        $data['datas'] = $this->db->row($sql);
        // $this->redisSetEx($redis_key, $data);
//        $this->redisSetEx($redis_key, $data);
//        }
        return $data;
    }
    # endregion

    # region Redis操作

    /**
     * 取Redis的值
     * @param $Redis object redis对象
     * @param $key string 要取值的redis字段名
     * @return mixed string|ing|array
     */
    public function redisGet($key){
        $value = $this->redis->get($key);
        $value_serl = @unserialize($value);
        if(is_object($value_serl)||is_array($value_serl)){
            return $value_serl;
        }
        return $value;
    }

    /**
     * 设置Redis数据
     * @param $Redis object redis对象
     * @param $key string 字段名
     * @param $value key对应的值（string|int|array）
     * @return mixed
     */
    public function redisSet($key, $value){
        if(is_object($value)||is_array($value)){
            $value = serialize($value);
        }
        return $this->redis->set($key,$value);
    }
    /**
     * 设置有时效性的Redis数据
     * @param $Redis object redis对象
     * @param $key string 字段名
     * @param $value key对应的值（string|int|array）
     * @param $value int 过期时间（秒）
     * @return mixed
     */
    public function redisSetEx($key, $value, $expire = 86400){
        if(is_object($value)||is_array($value)){
            $value = serialize($value);
        }
        return $this->redis->setex($key,$expire, $value);
    }

    /**
     * 检测LIST虽否存在对应的值
     * @param $redis object Redis对象
     * @param $key string 要查找的Redis键名
     * @param $value string 要检测的键值
     * @param int $Addition_subtraction 统计列表时是否加减总数
     * @return bool
     */
    public function existsRedisKey($key, $value)
    {
        $isHaveNuo = false;
        $_total = $this->redis->llen($key);
        $redis_key_index = 0;
        $redis_key_count = $_total;
        while($redis_key_index < $redis_key_count){
            $redis_key_item = $this->redis->lindex($key, $redis_key_index);
            if($redis_key_item == $value)
            {
                $isHaveNuo = true;
            }
            $redis_key_index++;
        }
        return $isHaveNuo;
    }

    public function rowRedis($key, $value){
        $_rows = $this->redisGet($key);
        return $_rows;
    }


    # endregion

    # region 数据库操作 - 无限返水
    public function agentBackCoin($args){
        global $db;

        $db_prefix = \Config\Json::$config['db_prefix'];
        $usertype = intval($args['usertype']);

        # 试玩用户不能有返水
        if($usertype > 0){
            $sql = "SELECT `uid`,`parentid`,`rebate`,`usertype`,`nickname` FROM `{$db_prefix}users` WHERE `uid`=".$args['parentid']." LIMIT 1";
            $parent = $db->row($sql);
            if($parent){
                # 返点 = 用户的上级返点 - 参与玩家的返点
                //$rebate = floatval($parent['rebate']) - floatval($args['rebate']);
                $rebate = floatval($parent['rebate']);
                $rebateCoin = floatval($args['ticket_winer']) * $rebate / 100;
                $backcoin = $this->formatCoin($rebateCoin);
                # 后期内部用户是否有返水的日志功能
                if(floatval($backcoin) > 0){
                    // echo "处理{$parent['uid']}-{$parent['nickname']}己的返水：{$backcoin}\n";
                    $this->setCoin(
                        array(
                            'uid' => $parent['uid'],
                            'coin' => floatval($this->formatCoin($backcoin)),
                            'gameid' => $args['gameid'],
                            'liqtype' => 24, //返水
                            'ex1' => $args['id'],
                            'ex2' => $args['issue'],
                            'ex3' => $args['nickname'] . '(' . $args['ticket_winer'] . '×' . $rebate . '%)',
                            'fromuid' => $args['uid'],
                        )
                    );
                    # 更新用户的余额及返水额
                    # $sql = 'UPDATE `' . $this->db_prefix . 'users` SET `coin` = `coin` + ' . $rebateCoin . ', `backtotal` = `backtotal` + ' . $rebateCoin . ' WHERE `uid` = ' . $parent['uid'] . ' LIMIT 1';
                    # $db->query($sql);

                }

                // print_r($_args);
//                self::agentBackCoin(array(
//                    'uid' => $parent['uid'],
//                    'usertype' => $parent['usertype'],
//                    'parentid' => $parent['parentid'],
//                    'fromuid' => $parent['uid'],
//                    'rebate' => $parent['rebate'],
//                    'gameid' => $args['gameid'],
//                    'id' => $args['id'],
//                    'issue' => $args['issue'],
//                    'nickname' => $parent['nickname'],
//                    'ticket_winer' => $args['ticket_winer'],
//                    'coinlogid' => 0,
//                ));
            }
        }
    }

    # endregion

    # region 数据库操作
    /**
     * 组装批量更新的SQL语句
     * @param $tableName string 要更新的表名
     * @param $keyFieldName string 表达式的关键字段名
     * @param $idsAndvalue array 对应关键字段的值和要更新后的值(array('0'=>array('id'=>1,'value'=>100)))
     * @return string
     */
    public function batchUpdateTable($tableName,$keyFieldName,$idsAndvalue)
    {
        $update_sql = "UPDATE `{$tableName}` SET ";
        $set_key = array();
        $set_value = array();
        $ids = "0";
        foreach ($idsAndvalue as $k=>$v) {
            $ids .= ",".$v[$keyFieldName];
            foreach ($v['value'] as $key=>$val)
            {
                $set_key[$key] = "`{$key}`= CASE `{$keyFieldName}`";
                $count_val = (is_array($val) ? count($val) : 1);
                if(!isset($set_value[$key])) $set_value[$key] = "";
                for ($i=0;$i<$count_val;$i++)
                {
                    $set_value[$key] .= " WHEN {$v[$keyFieldName]} THEN '{$val}'";
                }
            }
        }
        //重新组装SQL
        foreach ($set_key as $key=>$val){
            $update_sql .= $val . $set_value[$key] . ' END,';
        }
        $update_sql = substr($update_sql, 0, -1);
        $update_sql .= " WHERE {$keyFieldName} IN({$ids})";
        return $update_sql;
    }
    /**
     * 保存充值订单
     * @param $paras array 组装后的URL参数
     * @param $payline
     */
    public function insertRechargeToDb($paras, $payline)
    {
        global $db;
        global $utility;

        $db_prefix = \Config\Json::$config['db_prefix'];

        # 生成订单号
        $rechargeid = $utility->neworderno();

        # 保存到充值日志中
        $recharge_log = array(
            'uid' => $paras['uid'],
            'usertype' => $paras['usertype'],
            'rechargeid' => $rechargeid,
            'amount' => $paras['amount'],
            'coin' => $paras['usercoin'],
            'bankid' => $payline['bankid'],
            'paywayid' => $payline['paywayid'],
            'lineid' => $payline['id'],
            'actiontime' => $paras['nowtime'],
            'transfername' => $paras['transfername'],
            'info' => '用户充值',
        );
        $db->insert($db_prefix.'users_recharge')->cols($recharge_log)->query();
        return $rechargeid;
    }
    /**
     * 保存提现订单
     * @param $paras array 组装后的URL参数
     */
    public function insertCashToDb($paras)
    {
        global $db;
        global $utility;

        # 生成订单号
        $cashid = $utility->neworderno();

        $cash_log = array(
            'uid' => $paras['uid'],
            'cashid' => $cashid,
            'bankid' => $paras['bankid'],
            'amount' => $paras['amount'],
            'coin' => $paras['usercoin'],
            'cashtime' => $paras['nowtime'],
            'actionuid'=> 0,
            'actionip'=>0,
            'actiontime'=> 0,
        );
        $db->insert($utility->db_prefix.'users_cash')->cols($cash_log)->query();
        return $cashid;
    }
    /**
     * 用户帐变记录
     * @param $db
     * @param $log
     */
    public function setCoin($log,$db_ym = ''){
        //IN `uid` int,`gameid` int,`coin` float,`liqtype` int,`ex1` int,`ex2` varchar
        $default = array(
            'uid' => (array_key_exists('uid',$log) ? $log['uid'] : 0),
            'gameid' => (array_key_exists('gameid',$log) ? $log['gameid'] : 0),
            'coin' => (array_key_exists('coin',$log) ? $log['coin'] : 0),
            'liqtype' => (array_key_exists('liqtype',$log) ? $log['liqtype'] : 1),
            'ex1' => (array_key_exists('ex1',$log) ? $log['ex1'] : 0),
            'ex2' => (array_key_exists('ex2',$log) ? $log['ex2'] : ''),
            'ex3' => (array_key_exists('ex3',$log) ? $log['ex3'] : ''),
            'fromuid' => (array_key_exists('fromuid',$log) ? $log['fromuid'] : 0),
        );
        $autoSend = $this->db->row('SELECT count(1) as num FROM `' . \Config\Sys::$dbprefix . 'autosend` WHERE `uid`= '.$default['uid']);
        if( $autoSend['num'] != 0 ){
            return;
        }
        $db_ym =  $db_ym ? :date('Ym');
        if(floatval($default['coin']) != 0) {
            //try {
            //$this->db->beginTrans();
            # 取出系统设置的最大返水 12%

            # 取出当前用户的返水 1%

            # 取出当前用户的上级用户返水 2% 那它的上级返水就是 2% - 1% = 1%
            # 一直扣到0为止


            $sql = 'UPDATE `' . $this->db_prefix . 'users` SET `coin` = `coin` + ' . $default['coin'] . ' WHERE `uid` = ' . $default['uid'] . ' LIMIT 1';
            if($default['liqtype'] == 24){
                $sql = 'UPDATE `' . $this->db_prefix . 'users` SET `coin` = `coin` + ' . $default['coin'] . ', `backtotal` = `backtotal` + ' . $default['coin'] . ' WHERE `uid` = ' . $default['uid'] . ' LIMIT 1';
            }
            $this->db->query($sql);

            $sql = 'SELECT `uid`,`coin`,`usertype`,`agentlevel`,`backtotal`,`betcoin`,`userlevel`,`parentid` FROM `' . $this->db_prefix . 'users` WHERE `uid`=' . $default['uid']. ' LIMIT 1';
            $user = $this->db->row($sql);
            # 添加资金流动日志
            $_coinlog = array(
                'gameid' => $default['gameid'],
                'uid' => $default['uid'],
                'coin' => $default['coin'],
                'usercoin' => $user['coin'],
                'times' => time(),
                'liqtype' => $default['liqtype'],
                'ex1' => $default['ex1'],
                'ex2' => $default['ex2'],
                'ex3' => $default['ex3'],
                'usertype' => $user['usertype'],
            );
            $_coinlog_insertID = $this->db->insert($this->db_prefix . 'coinlog_' . $db_ym)->cols($_coinlog)->query();



            # 处理玩家从普通玩家升级到代理
            $agentlevels = $this->getAgentLevelForRedis(0, true);

            //找出上级
            $sql = 'SELECT `uid`,`coin`,`usertype`,`agentlevel`,`backtotal`,`betcoin`,`userlevel`,`parentid` FROM `' . $this->db_prefix . 'users` WHERE `uid`=' . $user['parentid'] . ' LIMIT 1';
            $puser = $this->db->row($sql);
            # 统计邀请人的受邀人数 - 首次成为代理 - 首次成为代理需要满足（有充值且有参与额）
            if ($puser && empty($puser['agentlevel']) && $puser['usertype'] == 1) {
                $upagentnumbers = $this->getSystemParams('upagentnumbers');
                $sql = 'SELECT COUNT(1) AS __TOTAL FROM `' . \Config\Sys::$dbprefix . 'users` WHERE `usertype`>0 AND `recharge`>0 AND `betcoin`>0 AND `parentid`=' . $puser['uid'];
                $total = $this->db->row($sql);
                $total = $total['__TOTAL'];
                # 人数都满足时
                if ($total >= $upagentnumbers) {
                    # 找出预备代理等级行
                    $level = $this->getAgentLevelForLid(array('lid' => 0));//$agentlevels['agent'][0];
                    $sql = 'UPDATE `' . \Config\Sys::$dbprefix . 'users` SET `usertype`=2,`agentlevel`=' . $level['lid'].',`rebate`='.$level['backposion'].' WHERE `uid`=' . $puser['uid'] . ' LIMIT 1';
                    //$sql = 'UPDATE `' . \Config\Sys::$dbprefix . 'users` SET `usertype`=2,`rebate`='.$level['rebate'].' WHERE `uid`=' . $default['uid'] . ' LIMIT 1';
                    $this->db->query($sql);
                    # 是否发放晋级奖励
                    $agentupdategiveway = intval($this->getSystemParams('agentupdategiveway'));
                    # 如果 $agentupdategiveway 为 1 即发放晋级奖励，0不发放
                    if ($agentupdategiveway && floatval($level['promotionaward']) > 0) {
                        $this->setCoin(array(
                            'uid' => $puser['uid'],
                            'liqtype' => 30, // 晋级奖励
                            'gameid' => 0,
                            'coin' => $level['promotionaward'],
                            'ex1' => 0,
                            'ex2' => 0,
                            'ex3' => '会员晋级至' . $level['title'] . '奖励'
                        ));
                    }
                }
            }

            # 处理已经是代理的升级 - 如果是返水帐变 用户类型又是代理的 -
            # 处理代理等级
            if ($default['liqtype'] == 24 && $user['usertype'] == 2 ) {
                $level = $this->getAgentLevelForRedis($user['agentlevel'], false);
                if ($level) {
                    if ($user['backtotal'] >= $level['backtotal']) {
                        $this->db->query('UPDATE ' . $this->db_prefix . 'users SET `agentlevel`=' . $level['lid'] . ',`rebate`='.$level['backposion'] . ' WHERE `uid`=' . $default['uid'] . ' LIMIT 1');
                        # 晋级奖励大于 0 将记录到帐变中
                        if (floatval($level['promotionaward']) > 0) {
                            $oldlevel = $this->getAgentLevelForLid(array('lid' => $user['agentlevel']));
                            $this->setCoin(array(
                                'uid' => $default['uid'],
                                'liqtype' => 30, // 晋级奖励
                                'gameid' => 0,
                                'coin' => $level['promotionaward'],
                                'ex1' => 0,
                                'ex2' => 0,
                                'ex3' => $oldlevel['title'] . '晋级至' . $level['title'] . '奖励'
                            ));
                        }
                    }
                }
            }
            # 加入到用户的代理佣金明细中
            if ($default['liqtype'] == 24 && !empty($default['fromuid'])) {
                # 加入到佣金返水的明细中
                # uid,coin,actiontime,month
                $_backcoin = array(
                    'uid' => $default['uid'],
                    'fromuid' => $default['fromuid'],
                    'coin' => $default['coin'],
                    'actiontime' => time(),
                    'month' => date('m'),
                    'coinlogid' => $_coinlog_insertID,
                );
                $this->db->insert($this->db_prefix . 'backcoin')->cols($_backcoin)->query();
            }
            # 统计用户的充值总量
            if ($default['liqtype'] == 21 || $default['liqtype'] == 31) {
                # 更新用户的充值总金额
                $sql = "UPDATE `" . $this->db_prefix . "users` SET `recharge`=`recharge`+" . $default['coin'] . " WHERE `uid`=" . $default['uid'] . " LIMIT 1";
                $this->db->query($sql);
            }
            //} catch (Exception $e) {
            //    return $e->getMessage();
            //$this->db->rollBackTrans(); // 执行失败，事务回滚
            //}
        }
    }
    public function setScore($log){
        //IN `uid` int,`gameid` int,`coin` float,`liqtype` int,`ex1` int,`ex2` varchar
        /*
        $default = array(
            'uid' => 0,
            'gameid' => 0,
            'score' => 0,
            'liqtype' => 1,
            'ex1' => 0,
            'ex2' => '',
            'ex3' => '',
        );
        */
        $default = array(
            'uid' => (array_key_exists('uid',$log) ? $log['uid'] : 0),
            'gameid' => (array_key_exists('gamid',$log) ? $log['gameid'] : 0),
            'score' => (array_key_exists('score',$log) ? $log['score'] : 0),
            'liqtype' => (array_key_exists('liqtype',$log) ? $log['liqtype'] : 1),
            'ex1' => (array_key_exists('ex1',$log) ? $log['ex1'] : ''),
            'ex2' => (array_key_exists('ex2',$log) ? $log['ex2'] : ''),
            'ex3' => (array_key_exists('ex3',$log) ? $log['ex3'] : ''),
        );
        /*
        $sql = 'call setScore(';
        foreach ($default as $k => $v) {
            $val = (array_key_exists($k, $log) && $log[$k]) ? $log[$k] : $v;
            if ($v !== 0) $val = "'$val'";
            $sql .= $val.',';
        }
        $sql = substr($sql, 0, -1).')';
        $this->db->query($sql);
        */
        if($default['score'] != 0) {
            //try {
            $this->db->query('UPDATE `' . $this->db_prefix . 'users` SET `score` = `score` + ' . $default['score'] . ' WHERE `uid` = ' . $default['uid'] . ' LIMIT 1');
            $user = $this->db->row('SELECT `score`,`usertype` FROM `' . $this->db_prefix . 'users` WHERE `uid`=' . $default['uid'] . ' LIMIT 1');

            # 添加流动日志
            $_scorelog = array(
                'gameid' => $default['gameid'],
                'uid' => $default['uid'],
                'score' => $default['score'],
                'userscore' => $user['score'],
                'times' => time(),
                'liqtype' => $default['liqtype'],
                'ex1' => $default['ex1'],
                'ex2' => $default['ex2'],
                'ex3' => $default['ex3'],
                'usertype' => $user['usertype'],
            );
            $this->db->insert($this->db_prefix . 'scorelog')->cols($_scorelog)->query();
            //} catch (PDOException $e) {
            //$this->db->rollBackTrans(); // 执行失败，事务回滚
            //}
        }
    }

    public function totalTableRowsCount($sql){
        $sql_total = str_replace('~field~', 'COUNT(1) AS __total', $sql);
        $sql_total = str_replace('~limit~', '', $sql_total);
        $sql_total = str_replace('~order~', '', $sql_total);
        $db_total = $this->db->row($sql_total);
        $total = $db_total['__total'];
        return $total;
    }
    /**
     * 按SQL语句来取数据
     * @param $sql string 执行的SQL语句
     * @param $args array 参数数组，各项数值请参阅以下说明
     * @param $field string 要搜索的字段
     * @param $skip int 搜索当前的开始页数
     * @param $pagesize int 每页显示的行数
     * @param $order SQL的ORDER条件
     */
    public function  getTableRows($sql, $args)
    {
        $total = self::totalTableRowsCount($sql);
        $skip = (intval($args['page_current']) - 1) * $args['pagesize'];
        $pagesize = intval($args['pagesize']);

        $sql = str_replace('~field~', $args['field'], $sql);
        $sql = str_replace('~limit~', 'LIMIT ' . $skip . ',' . $pagesize, $sql);
        $sql = str_replace('~order~', $args['order'], $sql);

        //echo "getTableRows=".$sql."\n";

        $datas = $this->db->query($sql);
        return array(
            'datas' => $datas,
            'total' => $total,
        );
    }

    // 获取数据列表最大页码
    public function get_maxpage($psize,$total) {
        $page_max = $total>0 && $psize>0 ? ceil($total / $psize) : 1;
        return $page_max ? $page_max : 1;
    }

    /**
     * 处理页面URL提交的参数
     * @param $paras URL提交过来的参数
     * @param $mastArgs 需要处理的参数列表 格式：参数名|参数类型-默认字符型S|默认值-字符型为空
     * @return array
     */
    public function get_url_args($paras, $mastArgs)
    {
        $args = array();
        foreach($mastArgs as $key=>$val)
        {
            # 分隔参数 要检测的参数|参数返回的类型|默认值
            $args_arr = explode("|", $val);
            $keyName = $args_arr[0];
            # 默认为返回字符串，默认值为空字符串
            $defaultType = isset($args_arr[1]) ? $args_arr[1] : 'S';
            $defaultValue = isset($args_arr[2]) ? $args_arr[2] : '';
            if(empty($defaultValue)){
                $args[$keyName] = self::existsKey($keyName, $paras, $defaultType);
            }else{
                $args[$keyName] = self::existsKey($keyName, $paras, $defaultType, $defaultValue);
            }
        }
        return $args;
    }
    public function get_page_args($paras, $mastArgs)
    {
        $page_args = array();
        foreach($mastArgs as $key=>$val)
        {
            if (!empty($paras[$val])) $page_args[$val] = $paras[$val];
        }
        $page_args['pc'] = self::existsKey('pc',$paras,'N', 1);
        return $page_args;
    }
    # endregion

    # region 以POST方式提交到对应的接口url
    /**
     * 以post方式提交xml到对应的接口url
     *
     * @param string $xml  需要post的xml数据
     * @param string $url  url
     * @param bool $useCert 是否需要证书，默认不需要
     * @param int $second   url执行超时时间，默认30s
     * @throws WxPayException
     */
    public function postCurl($paras, $url, $useCert = array('use'=>FALSE,'cert'=>'','keys'=>''), $second = 30)
    {
        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);

        //如果有配置代理这里就设置代理
        if(WxPayConfig::CURL_PROXY_HOST != "0.0.0.0"
            && WxPayConfig::CURL_PROXY_PORT != 0){
            curl_setopt($ch,CURLOPT_PROXY, WxPayConfig::CURL_PROXY_HOST);
            curl_setopt($ch,CURLOPT_PROXYPORT, WxPayConfig::CURL_PROXY_PORT);
        }
        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);//TRUE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);//2);//严格校验
        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

        if($useCert['use'] == true){
            //设置证书
            //使用证书：cert 与 key 分别属于两个.pem文件
            curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
            curl_setopt($ch,CURLOPT_SSLCERT, $useCert['cert']);
            curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
            curl_setopt($ch,CURLOPT_SSLKEY, $useCert['keys']);
        }
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $paras);
        //运行curl
        $data = curl_exec($ch);
        //返回结果
        if($data){
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            curl_close($ch);
            throw new Exception('curl出错，错误码:'.$error);
        }
    }
    # endregion

    # region 以GET方式提交到对应的接口url

    public function curl_get_https($url){
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
        $tmpInfo = curl_exec($curl);     //返回api的json对象
        //关闭URL请求
        curl_close($curl);
        return $tmpInfo;    //返回json对象
    }
    # endregion

    # region 253短信接口
    /**
     * 发送短信
     *
     * @param string $mobile 		手机号码
     * @param string $msg 			短信内容
     * @param string $needstatus 	是否需要状态报告
     */
    public function sendSMS($mobile) {
        $result = array('state'=>404, 'msgid'=>10092);
        # 选择检测Redis中是否存这个验证码，如果存在即不再重新发送
        $redis_verify = self::redisGet('sms_'.$mobile);
        if($redis_verify){
            return $result;
        }
        $smsline = self::redisGet(Config\Sys::$redisKey['SMSLINE']);
        if(!$smsline){
            $sql = "SELECT * FROM `".\Config\Sys::$dbprefix."smsline` WHERE `state`=1 LIMIT 1";
            $smsline = $this->db->row($sql);
            self::redisSet(Config\Sys::$redisKey['SMSLINE'], $smsline);
        }

        $verify = mt_rand(100000,999999);

        $msg = $smsline['smscontent'];
        $msg = str_replace('{verify}', $verify, $msg);

        //创蓝接口参数
        $postArr = array (
            'account'  =>  $smsline['account'],
            'password' => $smsline['passwd'],
            'msg' => urlencode($msg),
            'phone' => $mobile,
            'report' => true
        );

        $result = $this->curlPostSMS( $smsline['apiurl'] , $postArr);

        $sms_log = array(
            'lineid' => $smsline['id'],
            'phone' => $mobile,
            'verify' => $verify,
            'actiontimes' => time(),
            'state' => 0,
            'sendstate' => 0,
        );


        if(!is_null(json_decode($result))){
            $output=json_decode($result,true);
            if(isset($output['code'])  && $output['code']=='0'){
                # 短信发送成功，记录到数据
                $sms_log['sendstate'] = 1;
                $result = array('state'=>200, 'msgid'=>10091);
                # 发送成功后记录到Redis中
                self::redisSetEx('sms_'.$mobile, $verify, 300);
                $this->db->insert(\Config\Sys::$dbprefix.'smsverify')->cols($sms_log)->query();
            }else{
                # 短信发送失败
                $sms_log['sendstate'] = 0;
                $result = array('state'=>404, 'msgid'=>10090, 'result'=>$output);
            }
        }
        return $result;
    }

    public function curlPostSMS($url,$postFields){
        $postFields = json_encode($postFields);
        $ch = curl_init ();
        curl_setopt( $ch, CURLOPT_URL, $url );
        curl_setopt( $ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8'
            )
        );
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt( $ch, CURLOPT_POST, 1 );
        curl_setopt( $ch, CURLOPT_POSTFIELDS, $postFields);
        curl_setopt( $ch, CURLOPT_TIMEOUT,1);
        curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0);
        $ret = curl_exec ( $ch );
        if (false == $ret) {
            $result = curl_error(  $ch);
        } else {
            $rsp = curl_getinfo( $ch, CURLINFO_HTTP_CODE);
            if (200 != $rsp) {
                $result = "请求状态 ". $rsp . " " . curl_error($ch);
            } else {
                $result = $ret;
            }
        }
        curl_close ( $ch );
        return $result;
    }
    # endregion

    # region 用户的VIP等级列表
    public function userlevels(){

    }
    # endregion

    # region 处理用户的VIP升级
    public function updateUserVip($uid){

        $sql = "SELECT `userlevel`,`recharge`,`betcoin`,`usertype` FROM `{$this->db_prefix}users` WHERE uid={$uid} LIMIT 1";
        $rdb = $this->db->row($sql);

        $betcoin = $rdb['betcoin'];
        $recharge = $rdb['recharge'];

        # 下一个VIP等级
        $sql = "SELECT l.`lid`,l.`title`,l.`cointotal`,l.`rechargesum`,u.`userlevel`,l.`promotionaward` FROM `{$this->db_prefix}userlevel` l,`{$this->db_prefix}users` u WHERE l.`lid`>u.`userlevel` AND u.`uid`={$uid} ORDER BY l.`lid` ASC LIMIT 1";
        $level = $this->db->row($sql);
        if($level) {
            # 比较是否适合升级的条件
            if ($recharge >= $level['rechargesum'] && $betcoin >= $level['cointotal']) {
                $sql = 'UPDATE `' . $this->db_prefix . 'users` SET `userlevel` = ' . $level['lid'] . ' WHERE `uid` = ' . $uid . ' LIMIT 1';
                $this->db->query($sql);

                $vipupdategiveway = intval($this->getSystemParams('vipupdategiveway'));

                # 如果VIP升级按晋级奖励，1发放，0不发放
                if ($vipupdategiveway && floatval($level['promotionaward']) > 0) {
                    $this->setCoin(array(
                        'uid' => $uid,
                        'liqtype' => 29, // 晋级奖励
                        'gameid' => 0,
                        'coin' => $level['promotionaward'],
                        'ex1' => 0,
                        'ex2' => 0,
                        'ex3' => 'VIP' . $rdb['userlevel'] . '升至VIP' . $level['lid'] . '晋级奖励'
                    ));
                }
            }
        }
    }
    # endregion

    # region 按概率出现0或1的数字过程
    public function getRandomNumbers($array)
    {
        $numAll = 10000;
        $res = 0;
        //中奖概率基数
        $num = array_sum($array) * $numAll;//当前一等奖概率1/10000
        foreach ($array as $k => $v) {
            $v = $v * $numAll; //90000
            //获取一个1到当前基数范围的随机数
            $rand = mt_rand(1, $num);//1
            if ($rand <= $v) {//1/10的概率
                //假设当前奖项$k=2,$v<=5才能中奖
                $res = $k;
                break;
            } else {
                //假设当前奖项$k=6,$v>1900,则没中六等奖,总获奖基数2000-1900,前五次循环都没中则2000-1-5-10-24-60=1900,必中6等奖,哈哈
                $num -= $v;//90000
            }
        }
        return $res;
    }
    # endregion

    # region 随机头像列表
    public function roundAvatarList(){
        $redis_key = \Config\Sys::$redisKey['ROUNDAVATAR'];
        $result = $this->redisGet($redis_key);
        if (!$result) {
            $sql = "SELECT `imgurl` FROM `".\Config\Sys::$dbprefix."avatar`";
            $result = $this->db->query($sql);
            $this->redisSet($redis_key, $result);
        }
        return $result;
    }
    # endregion

    # region 取出概率用户表
    public function getUsersProbabilityList($reload=false)
    {
        $redis_key = \Config\Sys::$redisKey['UPLIST'];
        $result = $this->redisGet($redis_key);
        # 当$reload = true 或 $result = false
        if (!$result) {
            //$probabilitytimes = intval($this->getSystemParams('probabilitytimes'));
            $nowtime = time();// - $probabilitytimes;
            $db_prefix = \Config\Sys::$dbprefix;
            $sql = "SELECT * FROM `{$db_prefix}users_probability` WHERE `effectivetime` >= (".$nowtime."-`jointime`) ORDER BY `uid` DESC";
            $result = $this->db->query($sql);
            $this->redisSet($redis_key, $result);
        }
        return $result;
    }
    # endregion

    # region 计算用户的实际充值(用户提现限制及盈亏概率计算)
    # 目前只计算用户当天金额
    /**
     * @param $uid 用户的 UID
     * @param $userprofit 用户的赢概率
     * @return recharge float 返回计算今天充值的金额
     * @return profit float 返回今天赢利的金额
     */
    public function userRealityRecharge($uid, $userprofit = 0){
        # 默认最后一天的充值金额为 0 充值金额和时间截
        $lastRechargeAmount = 0;
        $lastRechargeTimes = strtotime(date('Y-m-d',time()));
        # 取出最后一笔充值金额及时间截
        $sql = "SELECT IFNULL(SUM(`rechargeamount`),0) AS _TOTAL FROM `".\Config\Sys::$dbprefix."users_recharge` WHERE `uid`=".$uid." AND `state`=1 AND `actiontime`>={$lastRechargeTimes} ORDER BY `id` DESC LIMIT 1";
        //print_r($sql);
        $lastRecharge = $this->db->row($sql);
        if($lastRecharge){
            $lastRechargeAmount = $lastRecharge['_TOTAL'];
            # $lastRechargeTimes = $lastRecharge['actiontime'];
        }
        $_transfer_log_time = "`times` >= " . $lastRechargeTimes;
        $_betlog_time = "`times` >= " . $lastRechargeTimes;
        $_exchange_orders_time = "`actiontime` >= " . $lastRechargeTimes;
        $sql = "SELECT
                    u.`uid`,
                    u.`uno`,
                    u.`recharge`,
                    u.`coin`,
                    ( SELECT IFNULL( SUM( inred.`coin` ), 0 ) FROM `rp_transfer_log` inred WHERE inred.`touid` = u.`uid` AND inred.{$_transfer_log_time} ) AS inredcoin,
                    ( SELECT IFNULL( SUM( bets.`profit` ), 0 ) FROM `rp_betslog` bets WHERE bets.`uid` = u.`uid` AND bets.{$_betlog_time} ) AS profit,
                    ( SELECT IFNULL( SUM( outred.`coin` ), 0 ) FROM `rp_transfer_log` outred WHERE outred.`fromuid` = u.`uid` AND outred.{$_transfer_log_time} ) AS outredcoin,
                    ( SELECT IFNULL( SUM( ex.`amount` ), 0 ) FROM `rp_exchange_orders` ex WHERE ex.`uid` = u.`uid` AND ex.{$_exchange_orders_time} ) AS excoin 
                FROM
                    `rp_users` u 
                WHERE
                    u.`uid` =" . $uid;

        $ur = $this->db->row($sql);
        # 如果当天没有充值用户的充值金额将按用户的余额来计算
        # 可能产生的问题：用户赢到了概率值的金额后，只取赢的金额，本金留着，后续要如何处理
        #if($lastRechargeAmount == 0){
        #    $lastRechargeAmount = $ur['coin'];
        #}
        # 实际的充值 = 充值 + 传进来的包 - 传出去的包 - 兑换消费的金额
        # $rechargeCoin = floatval($ur['recharge']) + floatval($ur['inredcoin']) - floatval($ur['outredcoin']) - floatval($ur['excoin']);
        # 2018-09-11 修改：充值的最后一笔金额时间为准的充值金额 + 充值时间后传进来的包 - 充值时间后传出去的包 - 充值时间后兑换消费的金额
        $rechargeCoin = floatval($lastRechargeAmount) + floatval($ur['inredcoin']) - floatval($ur['outredcoin']) - floatval($ur['excoin']);
        // print_r($rechargeCoin);
        // echo "\n";
        return array(
            'recharge' => $rechargeCoin,
            'profit' => $ur['profit'],
        );
    }
    # endregion

    # region 取出对应游戏的抢发参数
    public function getGameSendGrabParas($gameid)
    {
        $redis_key = \Config\Sys::$redisKey['SGPARAMS'] . $gameid;
        $result = $this->redisGet($redis_key);
        if (!$result) {
            $sql = "SELECT * FROM `".\Config\Sys::$dbprefix."auto_sb_params` WHERE `gameid`=".$gameid;
            $result = $this->db->row($sql);
            $this->redisSet($redis_key, $result);
        }
        return $result;
    }
    # endregion

    # region 红包分配预结算过程
    /**
     * 先概率用户-》内部会员-》正常玩家
     * 概率用户：系统默认的输赢比率，用户独立设置的输赢比率
     * 内部会员：如果一包中内部会员占超过80%将随机开奖，超过50%取去两头取中间数据，只点25%以下，将取
     * 正常玩家：以上两种分配完后分配给正常玩家
     * @param $grabusers
     * @param $game
     */
    public function pretreatmentGameOld($game, $grabUsers, $redEnvelopes, $roundRedPackets, $pretreatment = false){

        $funcDebug = true;

        # ===== Show Debug info =======
        if($funcDebug) {
            echo "========== " . $redEnvelopes['issue'] . " 【红包分配策略 - Begin 】\n";
        }
        # ==== End Debug info ==========

        # 1 => 正常玩家，2=>概率玩家，3=>内部玩家
        # 选择计算当前包中概率用户、内部玩家、正常玩家的人数比率
        # 当前包有几个概率玩家
        # 当前用户是否为发包用户
        # 用户赢的概率（分玩家和机器人）
        # 当正常玩家只有一个时，按随机来开户概率运算
        # $_round = array(1,0,1,0,0,1,1,0,1,0); # 当正常玩家数不足时的随机概率，为1时不开启概率计算，将采用随机分配
        $_round = explode(':', $this->getSystemParams('gameroundswitch'));
        $roundPret = $this->getRandomNumbers($_round);
        $roundPret = ($roundPret ? 0 : 1);

        $_log = array(
            'psw' => 0, // 庄家稳赢
            'issue' => $redEnvelopes['issue'],
            'play' => $game['grabUsersTypeNumbers']['play'],
            'inside' => $game['grabUsersTypeNumbers']['self'],
            'pret' => $game['grabUsersTypeNumbers']['pret'],
            'rint' => $roundPret,
            'bankerwon' => 0, // 指定玩家稳赢的随机数值
        );
        if($pretreatment) $_log['psw'] = 1;
        if ($game['grabUsersTypeNumbers']['play'] <= 1
            AND $roundPret
            AND $game['grabUsersTypeNumbers']['pret'] <= 1
            AND $game['grabUsersTypeNumbers']['self'] >= ($redEnvelopes['need'] - 1)
        ){
            if($funcDebug) {
                echo "随机检测 1 - _play <=1 AND _round = ".$roundPret." AND _pret <=1 AND _self >= ".($redEnvelopes['need'] - 1)." \n";
            }
            $pretreatment = false;
            $_log['psw']  = 0;
        }
        # 如果概率玩家占全部玩家多数将不开启概率
        if($game['grabUsersTypeNumbers']['pret'] >= ($redEnvelopes['need'] - 1)){
            if($funcDebug) {
                echo "随机检测 2 - _self >= ".($redEnvelopes['need'] - 1)." \n";
            }
            $pretreatment = false;
            $_log['psw']  = 0;
        }
        # 如果全是内部玩家占全部玩家将不开启概率
        if($game['grabUsersTypeNumbers']['self'] == $redEnvelopes['need']){
            if($funcDebug) {
                echo "随机检测 3 - _self == ".($redEnvelopes['need'])." \n";
            }
            $pretreatment = false;
            $_log['psw']  = 0;
        }

        # 取出游戏的抢发参数
        $game_sb_paras = $this->getGameSendGrabParas($game['game']['id']);
        # 如果单个游戏的概率没有开启，也将随机
        if(intval($game_sb_paras['probability']) == 0)
        {
            if($funcDebug) {
                echo "单个游戏概率开关 - _game_sb_paras_probability == ".($game_sb_paras['probability'])." \n";
            }
            $pretreatment = false;
            $_log['psw']  = 0;
        }

        # 如果系统设置的概率开关为关即不开概率算法
        $sysPreSwitch = intval($this->getSystemParams('enablegameroundswitch'));
        if(!$sysPreSwitch){
            if($funcDebug) {
                echo "系统概率总开关 - _sysPreSwitch == ".($sysPreSwitch)." \n";
            }
            $pretreatment = false;
            $_log['psw']  = 0;
        }

        # 庄家稳赢概率
        $_bankerWonRoundList = explode(':', $game['game']['roundlist']);
        # 2:8 , 0 => 2,1 => 8 0 就是庄家稳赢
        $_log['bankerwon'] = $this->getRandomNumbers($_bankerWonRoundList);
        $_log['bankerwon'] = ($_log['bankerwon'] ? 0 : 1);

        /*
        echo $redEnvelopes['issue'] . " - " . $_info;
        echo ' 正常玩家：' . $game['grabUsersTypeNumbers']['play'];
        echo ' 概率玩家：' . $game['grabUsersTypeNumbers']['pret'];
        echo ' 机器人：' . $game['grabUsersTypeNumbers']['self'];
        echo ' 随机种子值：' . $_round[$roundPret];
        echo "\n";
        */
        $max_card_delete = false; // 是否删除最大（牌型）的红包
        $tempUser = $grabUsers;
        # 记录发包用户
        $bankerUser = $grabUsers[0];

        $functionRunBeginTimes = microtime(true);

        switch ($game['game']['id']){
            case 1:

                # 最小红包
                $minArrIndex = array_search(min($roundRedPackets), $roundRedPackets);
                $min = $roundRedPackets[$minArrIndex];

                # 最大红包
                $maxArrIndex = array_search(max($roundRedPackets), $roundRedPackets);
                $max = $roundRedPackets[$maxArrIndex];

                # 开概率后，最小的包不分配给概率用户及内部用户
                if($pretreatment) {

                    if($_log['bankerwon']) {
                        if($funcDebug) {
                            echo "概率开启 - 庄家稳赢模式 - _bankerwon = ".$_log['bankerwon']." \n";
                        }
                        $grabUsers[0]['coin'] = $max['coin'];
                        unset($tempUser[0]);
                    }

                    # 删除最小红包的行
                    unset($roundRedPackets[$minArrIndex]);
                    //$min = array_splice($roundRedPackets, $pos, 1);

                    # 如果概率用户没有机会拿最大的包及庄家稳赢的情况下，将它删除
                    if($_log['bankerwon'] || intval($game_sb_paras['grabbig']) == 0) {
                        unset($roundRedPackets[$maxArrIndex]);
                    }



                    # 先分配概率用户
                    if ($game['grabUsersTypeNumbers']['pret'] >= 1) {
                        if($funcDebug) {
                            echo "分配概率玩家 - _pret = ".$game['grabUsersTypeNumbers']['pret']."\n";
                        }
                        foreach ($tempUser as $k => $v) {
                            if ($v['pointstype'] == 2) { // 概率用户
                                $arr = $this->randArrayCoin($roundRedPackets);
                                $grabUsers[$k]['coin'] = $arr['coin'];
                                //重新组织红包数据，这个数据是删除刚刚取出那行后的新数据
                                unset($roundRedPackets[$arr['key']]);
                                unset($tempUser[$k]);
                            }
                        }
                    }

                    # 压入最小的红包 - 内部玩家也是有机会拿到最小的红包

                    array_push($roundRedPackets, $min);
                    # 如果 概率用户没有机会拿最大 及 不是庄家稳赢 没有正常玩家 的情况下，将它加入
                    if (!$_log['bankerwon'] && intval($game_sb_paras['grabbig']) == 0) {
                        array_push($roundRedPackets, $max);
                    }

                    # 然后分配内部用户
                    if ($game['grabUsersTypeNumbers']['self'] >= 1) {
                        if($funcDebug) {
                            echo "分配内部玩家 - _self = ".$game['grabUsersTypeNumbers']['self']."\n";
                        }
                        foreach ($tempUser as $k => $v) {
                            if ($v['pointstype'] == 3) { // 内部用户
                                $arr = $this->randArrayCoin($roundRedPackets);
                                $grabUsers[$k]['coin'] = $arr['coin'];
                                //重新组织红包数据，这个数据是删除刚刚取出那行后的新数据
                                unset($roundRedPackets[$arr['key']]);

                                unset($tempUser[$k]);
                            }
                        }
                    }

                    # 最后分配正常玩家
                    if ($game['grabUsersTypeNumbers']['play'] >= 1) {
                        if($funcDebug) {
                            echo "分配正常玩家 - _play = ".$game['grabUsersTypeNumbers']['play']."\n";
                        }
                        # 把最小的红包也加进去
                        // array_push($roundRedPackets, $min);
                        foreach ($tempUser as $k => $v) {
                            if ($v['pointstype'] == 1) { // 正常用户
                                $arr = $this->randArrayCoin($roundRedPackets);
                                $grabUsers[$k]['coin'] = $arr['coin'];
                                //重新组织红包数据，这个数据是删除刚刚取出那行后的新数据
                                unset($roundRedPackets[$arr['key']]);
                            }
                        }
                    }
                }else{
                    if($funcDebug) {
                        echo "随机分配红包 \n";
                    }
                    if($_log['bankerwon']){
                        if($funcDebug) {
                            echo "随机分配 - 庄家稳赢模式 - _bankerwon = ".$_log['bankerwon']." \n";
                        }
                        $grabUsers[0]['coin'] = $max['coin'];
                        $grabUsers[0]['coin'] = $max['coin'];
                        unset($roundRedPackets[$maxArrIndex]);
                        unset($tempUser[0]);
                    }
                    foreach ($tempUser as $k => $v) {
                        $arr = $this->randArrayCoin($roundRedPackets);
                        $grabUsers[$k]['coin'] = $arr['coin'];
                        //重新组织红包数据，这个数据是删除刚刚取出那行后的新数据
                        unset($roundRedPackets[$arr['key']]);
                    }
                }
                break;
            case 2:
                # 先计算牌型的大小
                $cardList = array();
                foreach($roundRedPackets as $k=>$v){
                    $coin = strval(number_format($v['coin'], 2, '.', ''));
                    $n1 = substr($coin,-2,1); //小数点第一位
                    $n2 = substr($coin,-1);   //小数点后二位
                    $winsort_odds_key = 'n'.(($n1+$n2) % 10); // 牛几

                    // 最后是最大的牌型：牛牛
                    if((($n1+$n2) % 10)==0){
                        $winsort_odds_key = "n0";
                    }
                    # ======================================================================================================
                    $cardList[$k]['coin'] = $coin;
                    //找出对应输赢的牌型顺序
                    $cardList[$k]['winsort'] = $this->getOddsWinSort($game['odds'],'cardtype', $winsort_odds_key, 'winsort');
                    //找出对应的赔率
                    $cardList[$k]['odds'] = $this->getOddsWinSort($game['odds'],'cardtype', $winsort_odds_key, 'odds');
                    //牌型名称
                    $cardList[$k]['cardtitle'] = $this->getOddsWinSort($game['odds'],'cardtype', $winsort_odds_key, 'cardtitle');
                    # 牌型赔率代码
                    $cardList[$k]['cardtype'] = $winsort_odds_key;

                }

                # 如果有两个以上的赔率是一样的，
                # 概率用户不一定就是稳赢的玩家，
                # 有可能随机分配到已去除一个最小赔率的牌型
                # 但可以确保概率用户不会拿到最小的牌型
                $cardList = $this->sortArray($cardList, 'winsort', "ASC");

                # var_dump($cardList[array_rand($this->shuffle_assoc($cardList))]);

                $maxArrIndex = count($cardList) - 1;

                # 取出牌型中winsort这一列的最小值
                $min = $cardList[0];
                # 取出牌型中winsort这一列的最大值
                $max = $cardList[$maxArrIndex];

                if($pretreatment) {

                    # ===== Show Debug info =======
                    if($funcDebug) {
                        echo "----- " . $redEnvelopes['issue'] . " _pretreatment = 1 【 概率启用 】---------\n";
                    }
                    # ==== End Debug info ==========

                    # 把最小牌型的红包出列
                    unset($cardList[0]);

                    # 如果 庄家随机最大的种子值为 1 将去除最大的牌型，留给庄家
                    if($_log['bankerwon']) {

                        # ===== Show Debug info =======
                        if($funcDebug) {
                            echo "-【 庄家稳赢模式 - _bankerwon = 1 】\n";
                        }
                        # ==== End Debug info ==========

                        # 对应输赢的牌型顺序
                        $grabUsers[0]['winsort'] = $max['winsort'];
                        # 对应的赔率
                        $grabUsers[0]['odds'] = $max['odds'];
                        # 牌型名称
                        $grabUsers[0]['cardtitle'] = $max['cardtitle'];
                        # 抢到的红包金额
                        $grabUsers[0]['coin'] = $max['coin'];
                        # 牌型赔率代码
                        $grabUsers[0]['cardtype'] = $max['cardtype'];
                        # 把庄家从列表中删除
                        unset($tempUser[0]);
                        # 把最大牌型的红包删除
                        unset($cardList[$maxArrIndex]);
                    }else{
                        if(intval($game_sb_paras['grabbig']) == 0){
                            # 把最大牌型的红包删除
                            unset($cardList[$maxArrIndex]);
                        }
                    }

                    #$cardList = $this->shuffle_assoc($cardList);

                    # 先分配概率用户
                    if ($game['grabUsersTypeNumbers']['pret'] >= 1) {

                        # ===== Show Debug info =======
                        if($funcDebug) {
                            echo "【 概率玩家 - Begin _pret >= 1 】\n";
                            echo "还有".count($cardList)."个红包\n";
                        }
                        # ==== End Debug info ==========

                        foreach ($tempUser as $k => $v) {
                            if ($v['pointstype'] == 2) { // 概率用户
                                # 随机取一个牌型结果
                                $arrKey = array_rand($cardList,1);
                                $arr = $cardList[$arrKey];
                                unset($cardList[$arrKey]);

                                # 对应输赢的牌型顺序
                                $grabUsers[$k]['winsort'] = $arr['winsort'];
                                # 对应的赔率
                                $grabUsers[$k]['odds'] = $arr['odds'];
                                # 牌型名称
                                $grabUsers[$k]['cardtitle'] = $arr['cardtitle'];
                                # 抢到的红包金额
                                $grabUsers[$k]['coin'] = $arr['coin'];
                                # 牌型赔率代码
                                $grabUsers[$k]['cardtype'] = $arr['cardtype'];
                                //重新组织数据
                                unset($tempUser[$k]);
                            }
                        }
                        # ===== Show Debug info =======
                        if($funcDebug) {
                            echo "【 概率玩家 - End 】\n";
                        }
                        # ==== End Debug info ==========
                    }

                    # 压入最小的红包 - 内部玩家也是有机会拿到最小的红包
                    array_push($cardList, $min);
                    # 如果 概率用户没有机会拿最大 及 不是庄家稳赢 的情况下，将它加入
                    if (!$_log['bankerwon'] && intval($game_sb_paras['grabbig']) == 0) {
                        array_push($roundRedPackets, $max);
                    }

                    # 然后分配内部用户
                    # 这里分配红包的时候会出问题，当只有一个正常玩家且是庄家时，
                    # 最小的红包不会被压进去，导致红包数会少一个
                    /*
                    if ($game['grabUsersTypeNumbers']['play'] == 0) {
                        array_push($cardList, $min);
                        if(!$_log['bankerwon'] && intval($game_sb_paras['grabbig']) == 0) {
                            array_push($cardList, $max);
                        }
                    }
                    if ($game['grabUsersTypeNumbers']['play'] >= 1) {
                        if(!$_log['bankerwon'] && intval($game_sb_paras['grabbig']) == 0) {
                            array_push($cardList, $max);
                        }
                    }

                    # 2018-08-11 10:21:08
                    # 如果是庄家稳赢，然后庄家又是正常玩家，也要把最小的包压进去
                    if($_log['bankerwon'] && $game['grabUsersTypeNumbers']['play'] == 1 && $bankerUser['uid'] == $grabUsers[0]['uid'])
                    {
                        array_push($cardList, $min);
                    }
                    */

                    if ($game['grabUsersTypeNumbers']['self'] >= 1) {

                        # ===== Show Debug info =======
                        if($funcDebug) {
                            echo "【 内部玩家 - Begin _self >= 1】  \n";
                            echo "还有".count($cardList)."个红包\n";
                        }
                        # ==== End Debug info ==========
                        foreach ($tempUser as $k => $v) {
                            if ($v['pointstype'] == 3) { // 内部用户
                                # 随机取一个牌型结果
                                $arrKey = array_rand($cardList,1);
                                $arr = $cardList[$arrKey];
                                unset($cardList[$arrKey]);

                                # 对应输赢的牌型顺序
                                $grabUsers[$k]['winsort'] = $arr['winsort'];
                                # 对应的赔率
                                $grabUsers[$k]['odds'] = $arr['odds'];
                                # 牌型名称
                                $grabUsers[$k]['cardtitle'] = $arr['cardtitle'];
                                # 抢到的红包金额
                                $grabUsers[$k]['coin'] = $arr['coin'];
                                # 牌型赔率代码
                                $grabUsers[$k]['cardtype'] = $arr['cardtype'];
                                //重新组织数据
                                unset($tempUser[$k]);
                            }
                        }

                        # ===== Show Debug info =======
                        if($funcDebug) {
                            echo "【 内部玩家 - End 】\n";
                        }
                        # ==== End Debug info ==========
                    }

                    # 最后分配正常玩家
                    if ($game['grabUsersTypeNumbers']['play'] >= 1) {

                        # ===== Show Debug info =======
                        if($funcDebug) {
                            echo "【 正式玩家 - Begin _play >= 1 】\n";
                            echo "还有".count($cardList)."个红包\n";
                        }
                        # ==== End Debug info ==========

                        # 加入最小的牌型
                        array_push($cardList, $min);

                        foreach ($tempUser as $k => $v) {
                            if ($v['pointstype'] == 1) { // 正常用户
                                # 随机取一个牌型结果
                                $arrKey = array_rand($cardList,1);
                                $arr = $cardList[$arrKey];
                                unset($cardList[$arrKey]);

                                # 对应输赢的牌型顺序
                                $grabUsers[$k]['winsort'] = $arr['winsort'];
                                # 对应的赔率
                                $grabUsers[$k]['odds'] = $arr['odds'];
                                # 牌型名称
                                $grabUsers[$k]['cardtitle'] = $arr['cardtitle'];
                                # 抢到的红包金额
                                $grabUsers[$k]['coin'] = $arr['coin'];
                                # 牌型赔率代码
                                $grabUsers[$k]['cardtype'] = $arr['cardtype'];
                                //重新组织数据
                                unset($tempUser[$k]);
                            }
                        }
                        # ===== Show Debug info =======
                        if($funcDebug) {
                            echo "【 正式玩家 - End 】\n";
                        }
                        # ==== End Debug info ==========
                    }
                    # ===== Show Debug info =======
                    if($funcDebug) {
                        echo "===== 【 概率算法 - End 】==========\n";
                    }
                    # ==== End Debug info ==========
                }else{
                    #$cardList = $this->shuffle_assoc($cardList);
                    # ===== Show Debug info =======
                    if($funcDebug) {
                        echo "【 随机分配 - Begin 】=====\n";
                    }
                    # ==== End Debug info ==========

                    if($_log['bankerwon']){
                        # 对应输赢的牌型顺序
                        $grabUsers[0]['winsort'] = $max['winsort'];
                        # 对应的赔率
                        $grabUsers[0]['odds'] = $max['odds'];
                        # 牌型名称
                        $grabUsers[0]['cardtitle'] = $max['cardtitle'];
                        # 抢到的红包金额
                        $grabUsers[0]['coin'] = $max['coin'];
                        # 牌型赔率代码
                        $grabUsers[0]['cardtype'] = $max['cardtype'];
                        # 把最大牌型的红包删除 --  在数组中删除最大的牌型
                        unset($cardList[$maxArrIndex]);
                        unset($tempUser[0]);
                    }

                    # 随机分配
                    //$tempUsersLen = count($tempUser) - 1;
                    //for($k=$tempUsersLen; $k>=0; $k--) {
                    foreach($tempUser as $k=>$v){
                        # 随机取一个牌型结果
                        $arrKey = array_rand($cardList,1);
                        $arr = $cardList[$arrKey];
                        unset($cardList[$arrKey]);

                        # 对应输赢的牌型顺序
                        $grabUsers[$k]['winsort'] = $arr['winsort'];
                        # 对应的赔率
                        $grabUsers[$k]['odds'] = $arr['odds'];
                        # 牌型名称
                        $grabUsers[$k]['cardtitle'] = $arr['cardtitle'];
                        # 抢到的红包金额
                        $grabUsers[$k]['coin'] = $arr['coin'];
                        # 牌型赔率代码
                        $grabUsers[$k]['cardtype'] = $arr['cardtype'];
                    }

                    # ===== Show Debug info =======
                    if($funcDebug) {
                        echo "【 随机分配 - End 】=====\n";
                    }
                    # ==== End Debug info ==========
                }
                # print_r($cardList);
                break;
            case 3:
                $mantissaCount = 0;
                # 先计算牌型的大小
                $cardList = array();


                # 如果指定庄家稳赢家，一定要在抢包玩家中出现一个雷
                # 重新生成直到有雷 或 重新生成了$replayLen次为止
                $replayNumbers = 1;
                $replayLen = $redEnvelopes['need'];
                $isHave = 0;
                if($_log['bankerwon'] && $mantissaCount <=0){
                    # ===== Show Debug info =======
                    if($funcDebug) {
                        echo "【庄家稳赢 - 必出雷 】\n";
                    }
                    # ==== End Debug info ==========
                    while($mantissaCount <= 0 && $replayNumbers <= $replayLen) {
                        //产生红包数据
                        # ===== Show Debug info =======
                        if($funcDebug) {
                            echo "第几".$replayNumbers."次分配红包\n";
                        }
                        # ==== End Debug info ==========
                        $roundRedPackets = $this->redPacketRound($redEnvelopes['coin'], $redEnvelopes['need']);
                        foreach ($roundRedPackets as $k => $v) {
                            # 当前分配到的红包的尾数
                            $coin = strval($this->formatCoin($v['coin']));
                            $current_mantissa = substr($coin, -1);   //小数点后二位
                            if ($redEnvelopes['mantissa'] == $current_mantissa) {
                                $mantissaCount++;
                                $isHave = 1;
                            }
                        }
                        $replayNumbers ++;
                    }
                    # 如果上面的数据没有产生雷，将手动重新生成红包数据
                }

                # 当庄家稳赢时，随机一个没有尾数的红包，并从红包表中删除
                $noMantissaArr = array();
                $noMantissaArrKey = -1;

                if($_log['bankerwon']) {
                    # ===== Show Debug info =======
                    if($funcDebug) {
                        echo "【庄家稳赢 - 取一个没有尾数的红包金额 Begin 】\n";
                    }
                    # ==== End Debug info ==========

                    foreach($roundRedPackets as $k=>$v){
                        $coin = strval($this->formatCoin($v['coin']));
                        $current_mantissa = substr($coin, -1);   //小数点后二位

                        if ($current_mantissa != $redEnvelopes['mantissa']) {
                            $noMantissaArr['coin'] = $v['coin'];
                            $noMantissaArr['mantissa'] = $current_mantissa;
                            $noMantissaArrKey = $k;
                            $isHave = 1;
                        }
                    }

                    if($funcDebug) {
                        echo "【庄家稳赢 - 取一个没有尾数的红包金额 Center   】\n";
                    }

                    # 如果实在没有出雷就随机取一个
                    if(!$isHave){
                        # ===== Show Debug info =======
                        if($funcDebug) {
                            echo "【庄家稳赢 - 所有红包都没有雷 - 随机取一个红包给庄家 】\n";
                        }
                        # ==== End Debug info ==========
                        # 默认随机取一个
                        $arr = $this->randArrayCoin($roundRedPackets);
                        $coin = strval($this->formatCoin($arr['coin']));
                        $current_mantissa = substr($coin, -1);   //小数点后二位
                        $noMantissaArr['coin'] = $arr['coin'];
                        $noMantissaArr['mantissa'] = $current_mantissa;
                        $noMantissaArrKey = $arr['key'];
                    }
                    if($funcDebug) {
                        echo "【庄家稳赢 - 取一个没有尾数的红包金额 End   】\n";
                    }
                }


                if($pretreatment){
                    if($_log['bankerwon']){
                        $grabUsers[0]['coin'] = $noMantissaArr['coin'];
                        $grabUsers[0]['mantissa'] = $noMantissaArr['mantissa'];
                        unset($roundRedPackets[$noMantissaArrKey]);
                        unset($tempUser[0]);
                    }
                    # 概率用户可能要后面计算，因为雷有可能会出现多次，在前面分配的玩家可能就比较有机会分配到
                    # 先分配概率用户
                    if ($game['grabUsersTypeNumbers']['pret'] >= 1) {
                        # ===== Show Debug info =======
                        if($funcDebug) {
                            echo "【概率玩家 - Begin 】\n";
                        }
                        # ==== End Debug info ==========
                        foreach ($tempUser as $k => $v) {
                            if ($v['pointstype'] == 2) { // 概率用户

                                # 随机取一个牌型结果
                                $arr = $this->randArrayCoin($roundRedPackets);
                                $coin = strval($this->formatCoin($arr['coin']));
                                $current_mantissa = substr($coin, -1);   //小数点后二位
                                $arr['mantissa'] = $current_mantissa;
                                unset($roundRedPackets[$arr['key']]);

                                $grabUsers[$k]['mantissa'] = $arr['mantissa'];
                                $grabUsers[$k]['coin'] = $arr['coin'];
                                unset($tempUser[$k]);
                            }
                        }
                        # ===== Show Debug info =======
                        if($funcDebug) {
                            echo "【概率玩家 - End   】\n";
                        }
                        # ==== End Debug info ==========
                    }
                    # 然后分配内部用户
                    if ($game['grabUsersTypeNumbers']['self'] >= 1) {
                        # ===== Show Debug info =======
                        if($funcDebug) {
                            echo "【内部玩家 - Begin 】\n";
                        }
                        # ==== End Debug info ==========
                        foreach ($tempUser as $k => $v) {
                            if ($v['pointstype'] == 3) { // 内部用户

                                # 随机取一个牌型结果
                                $arr = $this->randArrayCoin($roundRedPackets);
                                $coin = strval($this->formatCoin($arr['coin']));
                                $current_mantissa = substr($coin, -1);   //小数点后二位
                                $arr['mantissa'] = $current_mantissa;
                                unset($roundRedPackets[$arr['key']]);

                                $grabUsers[$k]['mantissa'] = $arr['mantissa'];
                                $grabUsers[$k]['coin'] = $arr['coin'];
                                unset($tempUser[$k]);
                            }
                        }
                        # ===== Show Debug info =======
                        if($funcDebug) {
                            echo "【内部玩家 - End   】\n";
                        }
                        # ==== End Debug info ==========
                    }

                    # 最后分配正常玩家
                    if ($game['grabUsersTypeNumbers']['play'] >= 1) {
                        # ===== Show Debug info =======
                        if($funcDebug) {
                            echo "【正常玩家 - Begin 】\n";
                        }
                        # ==== End Debug info ==========
                        foreach ($tempUser as $k => $v) {
                            if ($v['pointstype'] == 1) { // 正常用户

                                # 随机取一个牌型结果
                                $arr = $this->randArrayCoin($roundRedPackets);
                                $coin = strval($this->formatCoin($arr['coin']));
                                $current_mantissa = substr($coin, -1);   //小数点后二位
                                $arr['mantissa'] = $current_mantissa;
                                unset($roundRedPackets[$arr['key']]);

                                $grabUsers[$k]['mantissa'] = $arr['mantissa'];
                                $grabUsers[$k]['coin'] = $arr['coin'];

                                //重新组织数据
                                unset($tempUser[$k]);
                            }
                        }
                        # ===== Show Debug info =======
                        if($funcDebug) {
                            echo "【正常玩家 - Begin 】\n";
                        }
                        # ==== End Debug info ==========
                    }
                }else{
                    # ===== Show Debug info =======
                    if($funcDebug) {
                        echo "【随机分配 - Begin 】\n";
                    }
                    # ==== End Debug info ==========
                    if($_log['bankerwon']){
                        $grabUsers[0]['coin'] = $noMantissaArr['coin'];
                        $grabUsers[0]['mantissa'] = $noMantissaArr['mantissa'];
                        unset($roundRedPackets[$noMantissaArrKey]);
                        unset($tempUser[0]);
                    }
                    # 分配红包
                    foreach ($tempUser as $uk=>$uv) {
                        # 随机分配红包
                        $arr = $this->randArrayCoin($roundRedPackets);
                        $coin = strval($this->formatCoin($arr['coin']));
                        $current_mantissa = substr($coin, -1);   //小数点后二位
                        $grabUsers[$uk]['coin'] = $arr['coin'];
                        $grabUsers[$uk]['mantissa'] = $current_mantissa;
                        unset($roundRedPackets[$arr['key']]);
                    }
                    # ===== Show Debug info =======
                    if($funcDebug) {
                        echo "【随机分配 - End   】\n";
                    }
                    # ==== End Debug info ==========
                }
                break;

            # ---------------------------------------- 二八杠 预算过程 --------------------------------------------------
            case 4:
                # 先计算牌型的大小
                $cardList = array();
                foreach($roundRedPackets as $k=>$v){
                    $coin = strval(number_format($v['coin'], 2, '.', ''));

                    $n1 = substr($coin,-2,1); //小数点第一位
                    $n2 = substr($coin,-1);   //小数点后二位

                    # region 匹配设置好的红包牌型
                    $n1n2 = $n1 . $n2;

                    $cardtype_number = (($n1+$n2) % 10);
                    $winsort_odds_key = 'd0'; // 0点

                    # 白板+X点
                    if($n1=='0'){
                        $winsort_odds_key = 'b0d' . $n2;
                    }else{
                        # 点数
                        if(($n1+$n2) > 0){
                            $winsort_odds_key = 'd' . $cardtype_number;
                        }
                    }
                    # 二八杠
                    if($n1n2=='28'){
                        $winsort_odds_key = 'ebg28';
                    }
                    # 对子
                    if($n1 == $n2){
                        $winsort_odds_key = 'dz' . $n1;
                    }
                    # 对白板
                    if($n1n2=='00'){
                        $winsort_odds_key = 'd00';
                    }
                    # ======================================================================================================
                    $cardList[$k]['coin'] = $coin;
                    //找出对应输赢的牌型顺序
                    $cardList[$k]['winsort'] = $this->getOddsWinSort($game['odds'],'cardtype', $winsort_odds_key, 'winsort');
                    //找出对应的赔率
                    $cardList[$k]['odds'] = $this->getOddsWinSort($game['odds'],'cardtype', $winsort_odds_key, 'odds');
                    //牌型名称
                    $cardList[$k]['cardtitle'] = $this->getOddsWinSort($game['odds'],'cardtype', $winsort_odds_key, 'cardtitle');
                    # 牌型赔率代码
                    $cardList[$k]['cardtype'] = $winsort_odds_key;

                }

                # 如果有两个以上的赔率是一样的，
                # 概率用户不一定就是稳赢的玩家，
                # 有可能随机分配到已去除一个最小赔率的牌型
                # 但可以确保概率用户不会拿到最小的牌型
                $cardList = $this->sortArray($cardList, 'winsort', "ASC");

                $middenArr = $cardList;
                $maxArrIndex = count($cardList) - 1;

                # 取出牌型中winsort这一列的最小值
                $min = $middenArr[0];
                # 取出牌型中winsort这一列的最大值
                $max = $middenArr[$maxArrIndex];


                if($pretreatment) {

                    # ===== Show Debug info =======
                    if($funcDebug) {
                        echo "----- " . $redEnvelopes['issue'] . " _pretreatment = 1 【 概率启用 】---------\n";
                    }
                    # ==== End Debug info ==========

                    unset($cardList[0]);
                    # 把最大牌型的红包删除 --  在数组中删除最大的牌型
                    unset($cardList[$maxArrIndex]);

                    # 如果 庄家随机最大的种子值为 1 将去除最大的牌型，留给庄家
                    if($_log['bankerwon']) {
                        # ===== Show Debug info =======
                        if($funcDebug) {
                            echo "庄家稳赢模式 - 去除一个最大的牌型 \n";
                        }
                        # ==== End Debug info ==========
                        # 对应输赢的牌型顺序
                        $grabUsers[0]['winsort'] = $max['winsort'];
                        # 对应的赔率
                        $grabUsers[0]['odds'] = $max['odds'];
                        # 牌型名称
                        $grabUsers[0]['cardtitle'] = $max['cardtitle'];
                        # 抢到的红包金额
                        $grabUsers[0]['coin'] = $max['coin'];
                        # 牌型赔率代码
                        $grabUsers[0]['cardtype'] = $max['cardtype'];
                        # 把庄家从列表中删除
                        unset($tempUser[0]);
                    }
                    $cardList = $this->shuffle_assoc($cardList);
                    # 先分配概率用户
                    if ($game['grabUsersTypeNumbers']['pret'] >= 1) {
                        if($funcDebug) {
                            echo "分配概率玩家 _pret >=1 \n";
                            echo json_encode($cardList);
                            echo "--------------------------------------------------------\n";
                        }
                        foreach ($tempUser as $k => $v) {
                            if ($v['pointstype'] == 2) { // 概率用户

                                # 随机取一个牌型结果
                                $arrKey = array_rand($cardList,1);
                                $arr = $cardList[$arrKey];
                                unset($cardList[$arrKey]);

                                # 对应输赢的牌型顺序
                                $grabUsers[$k]['winsort'] = $arr['winsort'];
                                # 对应的赔率
                                $grabUsers[$k]['odds'] = $arr['odds'];
                                # 牌型名称
                                $grabUsers[$k]['cardtitle'] = $arr['cardtitle'];
                                # 抢到的红包金额
                                $grabUsers[$k]['coin'] = $arr['coin'];
                                # 牌型赔率代码
                                $grabUsers[$k]['cardtype'] = $arr['cardtype'];
                                //重新组织数据
                                unset($tempUser[$k]);
                            }
                        }
                    }
                    # 然后分配内部用户
                    if ($game['grabUsersTypeNumbers']['play'] == 0) {
                        array_push($cardList, $min);
                        if(!$_log['bankerwon']) {
                            array_push($cardList, $max);
                        }
                    }
                    if ($game['grabUsersTypeNumbers']['play'] >= 1) {
                        if(!$_log['bankerwon']) {
                            array_push($cardList, $max);
                        }
                    }
                    # 2018-08-11 10:21:08
                    # 如果是庄家稳赢，然后庄家又是正常玩家，也要把最小的包压进去
                    if($_log['bankerwon'] && $game['grabUsersTypeNumbers']['play'] == 1 && $bankerUser['uid'] == $grabUsers[0]['uid'])
                    {
                        array_push($cardList, $min);
                    }
                    if ($game['grabUsersTypeNumbers']['self'] >= 1) {
                        if($funcDebug) {
                            echo "分配内部玩家 _self >= 1\n";
                            echo json_encode($cardList);
                            echo "--------------------------------------------------------\n";
                        }
                        foreach ($tempUser as $k => $v) {
                            if ($v['pointstype'] == 3 && count($cardList) > 0) { // 内部用户
                                # 随机取一个牌型结果
                                $arrKey = array_rand($cardList,1);
                                $arr = $cardList[$arrKey];
                                unset($cardList[$arrKey]);

                                # 对应输赢的牌型顺序
                                $grabUsers[$k]['winsort'] = $arr['winsort'];
                                # 对应的赔率
                                $grabUsers[$k]['odds'] = $arr['odds'];
                                # 牌型名称
                                $grabUsers[$k]['cardtitle'] = $arr['cardtitle'];
                                # 抢到的红包金额
                                $grabUsers[$k]['coin'] = $arr['coin'];
                                # 牌型赔率代码
                                $grabUsers[$k]['cardtype'] = $arr['cardtype'];
                                //重新组织数据
                                unset($tempUser[$k]);
                            }
                        }
                    }

                    # 最后分配正常玩家
                    if ($game['grabUsersTypeNumbers']['play'] >= 1) {
                        # 加入最小的牌型
                        array_push($cardList, $min);
                        # 如果没有随机指定庄家拿到最大的牌型，把最大的牌型也加进去
                        //if(!$_log['bankerwon']) {
                        //    array_push($cardList, $max);
                        //}
                        if($funcDebug) {
                            echo "正常玩家 - cardList \n";
                            echo json_encode($cardList);
                            echo "--------------------------------------------------------\n";
                        }
                        foreach ($tempUser as $k => $v) {
                            if ($v['pointstype'] == 1) { // 正常用户

                                # 随机取一个牌型结果
                                $arrKey = array_rand($cardList,1);
                                $arr = $cardList[$arrKey];
                                unset($cardList[$arrKey]);

                                # 对应输赢的牌型顺序
                                $grabUsers[$k]['winsort'] = $arr['winsort'];
                                # 对应的赔率
                                $grabUsers[$k]['odds'] = $arr['odds'];
                                # 牌型名称
                                $grabUsers[$k]['cardtitle'] = $arr['cardtitle'];
                                # 抢到的红包金额
                                $grabUsers[$k]['coin'] = $arr['coin'];
                                # 牌型赔率代码
                                $grabUsers[$k]['cardtype'] = $arr['cardtype'];
                                //重新组织数据
                                unset($tempUser[$k]);
                            }
                        }
                    }
                }else{
                    if($funcDebug) {
                        echo "随机分配红包 \n";
                    }
                    # 如果庄家是随机指定为最大
                    if($_log['bankerwon']) {
                        # 对应输赢的牌型顺序
                        $grabUsers[0]['winsort'] = $max['winsort'];
                        # 对应的赔率
                        $grabUsers[0]['odds'] = $max['odds'];
                        # 牌型名称
                        $grabUsers[0]['cardtitle'] = $max['cardtitle'];
                        # 抢到的红包金额
                        $grabUsers[0]['coin'] = $max['coin'];
                        # 牌型赔率代码
                        $grabUsers[0]['cardtype'] = $max['cardtype'];
                        # 把最大牌型的红包删除 --  在数组中删除最大的牌型
                        unset($cardList[$maxArrIndex]);
                        unset($tempUser[0]);
                    }
                    # 随机分配
                    //$tempUsersLen = count($tempUser) - 1;
                    //for($k=$tempUsersLen; $k>=0; $k--) {
                    foreach($tempUser as $k=>$v){
                        # 随机取一个牌型结果
                        $arrKey = array_rand($cardList);
                        $arr = $cardList[$arrKey];
                        unset($cardList[$arrKey]);

                        # 对应输赢的牌型顺序
                        $grabUsers[$k]['winsort'] = $arr['winsort'];
                        # 对应的赔率
                        $grabUsers[$k]['odds'] = $arr['odds'];
                        # 牌型名称
                        $grabUsers[$k]['cardtitle'] = $arr['cardtitle'];
                        # 抢到的红包金额
                        $grabUsers[$k]['coin'] = $arr['coin'];
                        # 牌型赔率代码
                        $grabUsers[$k]['cardtype'] = $arr['cardtype'];
                    }
                }
                break;
            # ---------------------------------------------------------------------------------------------------------
            case 5:
                # 先计算牌型的大小
                $cardList = array();
                foreach($roundRedPackets as $k=>$v){
                    $coin = strval(number_format($v['coin'], 2, '.', ''));
                    $n1 = substr($coin,-2,1); //小数点第一位
                    $n2 = substr($coin,-1);   //小数点后二位

                    $winsort_odds_key = 'n'.(($n1+$n2) % 10); // 牛几

                    // 最后是最大的牌型：牛牛
                    if((($n1+$n2) % 10)==0){
                        $winsort_odds_key = "n0";
                    }
                    # ======================================================================================================
                    $cardList[$k]['coin'] = $coin;
                    //找出对应输赢的牌型顺序
                    $cardList[$k]['winsort'] = $this->getOddsWinSort($game['odds'],'cardtype', $winsort_odds_key, 'winsort');
                    //找出对应的赔率
                    $cardList[$k]['odds'] = $this->getOddsWinSort($game['odds'],'cardtype', $winsort_odds_key, 'odds');
                    //牌型名称
                    $cardList[$k]['cardtitle'] = $this->getOddsWinSort($game['odds'],'cardtype', $winsort_odds_key, 'cardtitle');
                    # 牌型赔率代码
                    $cardList[$k]['cardtype'] = $winsort_odds_key;

                }

                # 如果有两个以上的赔率是一样的，
                # 概率用户不一定就是稳赢的玩家，
                # 有可能随机分配到已去除一个最小赔率的牌型
                # 但可以确保概率用户不会拿到最小的牌型
                $cardList = $this->sortArray($cardList, 'winsort', "ASC");

                $middenArr = $cardList;
                $maxArrIndex = count($cardList) - 1;

                # 取出牌型中winsort这一列的最小值
                $min = $middenArr[0];
                # 取出牌型中winsort这一列的最大值
                $max = $middenArr[$maxArrIndex];


                if($pretreatment) {

                    unset($cardList[0]);
                    # 把最大牌型的红包删除 --  在数组中删除最大的牌型
                    unset($cardList[$maxArrIndex]);

                    # 如果 庄家随机最大的种子值为 1 将去除最大的牌型，留给庄家
                    if($_log['bankerwon']) {
                        # 对应输赢的牌型顺序
                        $grabUsers[0]['winsort'] = $max['winsort'];
                        # 对应的赔率
                        $grabUsers[0]['odds'] = $max['odds'];
                        # 牌型名称
                        $grabUsers[0]['cardtitle'] = $max['cardtitle'];
                        # 抢到的红包金额
                        $grabUsers[0]['coin'] = $max['coin'];
                        # 牌型赔率代码
                        $grabUsers[0]['cardtype'] = $max['cardtype'];
                        # 把庄家从列表中删除
                        unset($tempUser[0]);
                    }

                    $cardList = $this->shuffle_assoc($cardList);
                    # 先分配概率用户
                    if ($game['grabUsersTypeNumbers']['pret'] >= 1) {
                        foreach ($tempUser as $k => $v) {
                            if ($v['pointstype'] == 2) { // 概率用户

                                # 随机取一个牌型结果
                                $arrKey = array_rand($cardList,1);
                                $arr = $cardList[$arrKey];
                                unset($cardList[$arrKey]);

                                # 对应输赢的牌型顺序
                                $grabUsers[$k]['winsort'] = $arr['winsort'];
                                # 对应的赔率
                                $grabUsers[$k]['odds'] = $arr['odds'];
                                # 牌型名称
                                $grabUsers[$k]['cardtitle'] = $arr['cardtitle'];
                                # 抢到的红包金额
                                $grabUsers[$k]['coin'] = $arr['coin'];
                                # 牌型赔率代码
                                $grabUsers[$k]['cardtype'] = $arr['cardtype'];
                                //重新组织数据
                                unset($tempUser[$k]);
                            }
                        }
                    }
                    # 然后分配内部用户
                    if ($game['grabUsersTypeNumbers']['play'] == 0) {
                        array_push($cardList, $min);
                        if(!$_log['bankerwon']) {
                            array_push($cardList, $max);
                        }
                    }
                    if ($game['grabUsersTypeNumbers']['play'] >= 1) {
                        if(!$_log['bankerwon']) {
                            array_push($cardList, $max);
                        }
                    }
                    # 2018-08-11 10:21:08
                    # 如果是庄家稳赢，然后庄家又是正常玩家，也要把最小的包压进去
                    if($_log['bankerwon'] && $game['grabUsersTypeNumbers']['play'] == 1 && $bankerUser['uid'] == $grabUsers[0]['uid'])
                    {
                        array_push($cardList, $min);
                    }
                    if ($game['grabUsersTypeNumbers']['self'] >= 1) {
                        $cardList = $this->shuffle_assoc($cardList);
                        foreach ($tempUser as $k => $v) {
                            if ($v['pointstype'] == 3 && count($cardList ) > 0) { // 内部用户

                                # 随机取一个牌型结果
                                $arrKey = array_rand($cardList, 1);
                                $arr = $cardList[$arrKey];
                                unset($cardList[$arrKey]);

                                # 对应输赢的牌型顺序
                                $grabUsers[$k]['winsort'] = $arr['winsort'];
                                # 对应的赔率
                                $grabUsers[$k]['odds'] = $arr['odds'];
                                # 牌型名称
                                $grabUsers[$k]['cardtitle'] = $arr['cardtitle'];
                                # 抢到的红包金额
                                $grabUsers[$k]['coin'] = $arr['coin'];
                                # 牌型赔率代码
                                $grabUsers[$k]['cardtype'] = $arr['cardtype'];
                                //重新组织数据
                                unset($tempUser[$k]);
                            }
                        }
                    }

                    # 最后分配正常玩家
                    if ($game['grabUsersTypeNumbers']['play'] >= 1) {
                        # 加入最小的牌型
                        array_push($cardList, $min);
                        # 如果没有随机指定庄家拿到最大的牌型，把最大的牌型也加进去
                        //if(!$_log['bankerwon']) {
                        //    array_push($cardList, $max);
                        //}
                        foreach ($tempUser as $k => $v) {
                            if ($v['pointstype'] == 1  && count($cardList ) > 0) { // 正常用户

                                # 随机取一个牌型结果
                                $arrKey = array_rand($cardList, 1);
                                $arr = $cardList[$arrKey];
                                unset($cardList[$arrKey]);

                                # 对应输赢的牌型顺序
                                $grabUsers[$k]['winsort'] = $arr['winsort'];
                                # 对应的赔率
                                $grabUsers[$k]['odds'] = $arr['odds'];
                                # 牌型名称
                                $grabUsers[$k]['cardtitle'] = $arr['cardtitle'];
                                # 抢到的红包金额
                                $grabUsers[$k]['coin'] = $arr['coin'];
                                # 牌型赔率代码
                                $grabUsers[$k]['cardtype'] = $arr['cardtype'];
                                //重新组织数据
                                unset($tempUser[$k]);
                            }
                        }
                    }
                }else{
                    # 随机分配
                    //$grabUsersLen = count($grabUsers) - 1;
                    //for($k=$grabUsersLen; $k>=0; $k--) {
                    # 如果庄家是随机指定为最大
                    if($_log['bankerwon']) {
                        # 对应输赢的牌型顺序
                        $grabUsers[0]['winsort'] = $max['winsort'];
                        # 对应的赔率
                        $grabUsers[0]['odds'] = $max['odds'];
                        # 牌型名称
                        $grabUsers[0]['cardtitle'] = $max['cardtitle'];
                        # 抢到的红包金额
                        $grabUsers[0]['coin'] = $max['coin'];
                        # 牌型赔率代码
                        $grabUsers[0]['cardtype'] = $max['cardtype'];
                        # 把最大牌型的红包删除 --  在数组中删除最大的牌型
                        unset($cardList[$maxArrIndex]);
                        unset($tempUser[0]);
                    }
                    foreach ($tempUser as $k=>$v){
                        # 随机取一个牌型结果
                        $arrKey = array_rand($cardList, 1);
                        $arr = $cardList[$arrKey];

                        # 对应输赢的牌型顺序
                        $grabUsers[$k]['winsort'] = $arr['winsort'];
                        # 对应的赔率
                        $grabUsers[$k]['odds'] = $arr['odds'];
                        # 牌型名称
                        $grabUsers[$k]['cardtitle'] = $arr['cardtitle'];
                        # 抢到的红包金额
                        $grabUsers[$k]['coin'] = $arr['coin'];
                        # 牌型赔率代码
                        $grabUsers[$k]['cardtype'] = $arr['cardtype'];

                        unset($cardList[$arrKey]);
                    }
                }
                break;
        }
        $functionRunEndTimes = microtime(true);

        $this->db->insert(\Config\Sys::$dbprefix.'probability_log')->cols($_log)->query();

        # ===== Show Debug info =======
        if($funcDebug) {
            echo "========== " . $redEnvelopes['issue'] . " 【红包分配策略 - End - 耗时： ".(round(($functionRunEndTimes - $functionRunBeginTimes),3) * 1000)."ms】\n\n";
        }
        # ==== End Debug info ==========

        return $grabUsers;
    }

    public function pretreatmentGame($game, $grabUsers, $redEnvelopes, $roundRedPackets, $pretreatment = false){

        # 1 => 正常玩家，2=>概率玩家，3=>内部玩家
        # 选择计算当前包中概率用户、内部玩家、正常玩家的人数比率
        # 当前包有几个概率玩家
        # 当前用户是否为发包用户
        # 用户赢的概率（分玩家和机器人）
        # 当正常玩家只有一个时，按随机来开户概率运算
        # $_round = array(1,0,1,0,0,1,1,0,1,0); # 当正常玩家数不足时的随机概率，为1时不开启概率计算，将采用随机分配
        $_round = explode(':', $this->getSystemParams('gameroundswitch'));
        $roundPret = $this->getRandomNumbers($_round);
        $roundPret = ($roundPret ? 1 : 0);
        $_log = array(
            'psw' => 0, // 庄家稳赢
            'issue' => $redEnvelopes['issue'],
            'play' => $game['grabUsersTypeNumbers']['play'],
            'inside' => $game['grabUsersTypeNumbers']['self'],
            'pret' => $game['grabUsersTypeNumbers']['pret'],
            'rint' => $roundPret,
            'bankerwon' => 0, // 指定玩家稳赢的随机数值
        );
        if($pretreatment) $_log['psw'] = 1;
        if ($game['grabUsersTypeNumbers']['play'] == 1
            AND $roundPret
            //AND $game['grabUsersTypeNumbers']['pret'] <= 1
            AND $game['grabUsersTypeNumbers']['self'] >= ($redEnvelopes['need'] - 1)
        ){
            $pretreatment = false;
            $_log['psw']  = 0;
        }
        # 如果概率玩家占全部玩家多数将不开启概率
        if($game['grabUsersTypeNumbers']['pret'] >= ($redEnvelopes['need'] - 1)){
            $pretreatment = false;
            $_log['psw']  = 0;
        }
        # 如果全是内部玩家占全部玩家将不开启概率
        if($game['grabUsersTypeNumbers']['self'] == $redEnvelopes['need']){
            $pretreatment = false;
            $_log['psw']  = 0;
        }

        # 取出游戏的抢发参数
        $game_sb_paras = $this->getGameSendGrabParas($game['game']['id']);
        # 如果单个游戏的概率没有开启，也将随机
        if(intval($game_sb_paras['probability']) == 0)
        {
            $pretreatment = false;
            $_log['psw']  = 0;
        }

        # 如果系统设置的概率开关为关即不开概率算法
        $sysPreSwitch = intval($this->getSystemParams('enablegameroundswitch'));
        if(!$sysPreSwitch){
            $pretreatment = false;
            $_log['psw']  = 0;
        }

        # 庄家稳赢概率
        $_bankerWonRoundList = explode(':', $game['game']['roundlist']);
        # 2:8 , 0 => 2,1 => 8 0 就是庄家稳赢
        $_log['bankerwon'] = $this->getRandomNumbers($_bankerWonRoundList);
        $_log['bankerwon'] = ($_log['bankerwon'] ? 0 : 1);

        $tempUser = $grabUsers;
        # 记录发包用户
        $bankerUser = $grabUsers[0];
        /*
        if($game['game']['id'] == 1) {
            $pretreatment = true;
            $_log['psw'] = 1;
            $_log['bankerwon'] = 1;
        }
        */

        switch ($game['game']['id']){
            case 1:

                # 最小红包
                $minArrIndex = array_search(min($roundRedPackets), $roundRedPackets);
                $min = $roundRedPackets[$minArrIndex];

                # 最大红包
                $maxArrIndex = array_search(max($roundRedPackets), $roundRedPackets);
                $max = $roundRedPackets[$maxArrIndex];

                # 开概率后，最小的包不分配给概率用户及内部用户
                if($pretreatment) {

                    if($_log['bankerwon']) {
                        $grabUsers[0]['coin'] = $max['coin'];
                        unset($tempUser[0]);
                        # 删除最小红包的行
                        unset($roundRedPackets[$maxArrIndex]);
                    }else{
                        if(!$game_sb_paras['grabbig']){
                            unset($roundRedPackets[$maxArrIndex]);
                        }
                    }

                    # 删除最小红包的行
                    unset($roundRedPackets[$minArrIndex]);

                    # 先分配概率用户
                    if ($_log['pret'] >= 1) {
                        foreach ($tempUser as $k => $v) {
                            if ($v['pointstype'] == 2) { // 概率用户
                                $arr = $this->randArrayCoin($roundRedPackets);
                                $grabUsers[$k]['coin'] = $arr['coin'];
                                //重新组织红包数据，这个数据是删除刚刚取出那行后的新数据
                                unset($roundRedPackets[$arr['key']]);
                                unset($tempUser[$k]);
                            }
                        }
                    }

                    $isInMin = false;
                    # 如果机器人有机会拿到最小的红包 或 没有正常的玩家
                    if($game_sb_paras['grabmin']) {
                        //echo "加入最小的包1\n";
                        array_push($roundRedPackets, $min);
                        $isInMin = true;
                    }
                    if($_log['play'] == 0 && !$isInMin){
                        //echo "加入最小的包2\n";
                        array_push($roundRedPackets, $min);
                        $isInMin = true;
                    }
                    if($_log['bankerwon'] && !$isInMin && $_log['play']==1 && !empty($grabUsers[0]['coin'])){
                        //echo "加入最小的包2\n";
                        array_push($roundRedPackets, $min);
                        $isInMin = true;
                    }
                    # 如果 概率用户没有机会拿最大 及 不是庄家稳赢 没有正常玩家 的情况下，将它加入
                    if (!$_log['bankerwon'] && !$game_sb_paras['grabbig']) {
                        array_push($roundRedPackets, $max);
                    }

                    # 然后分配内部用户
                    if ($_log['inside'] >= 1) {
                        foreach ($tempUser as $k => $v) {
                            if ($v['pointstype'] == 3) { // 内部用户
                                $arr = $this->randArrayCoin($roundRedPackets);
                                $grabUsers[$k]['coin'] = $arr['coin'];
                                //重新组织红包数据，这个数据是删除刚刚取出那行后的新数据
                                unset($roundRedPackets[$arr['key']]);
                                unset($tempUser[$k]);
                            }
                        }
                    }

                    # 最后分配正常玩家
                    if ($_log['play'] >= 1) {
                        if(!$isInMin) {
                            array_push($roundRedPackets, $min);
                        }
                        foreach ($tempUser as $k => $v) {
                            if ($v['pointstype'] == 1) { // 正常用户
                                $arr = $this->randArrayCoin($roundRedPackets);
                                $grabUsers[$k]['coin'] = $arr['coin'];
                                //重新组织红包数据，这个数据是删除刚刚取出那行后的新数据
                                unset($roundRedPackets[$arr['key']]);
                            }
                        }
                    }
                }else{
                    if($_log['bankerwon']){
                        $grabUsers[0]['coin'] = $max['coin'];
                        $grabUsers[0]['coin'] = $max['coin'];
                        unset($roundRedPackets[$maxArrIndex]);
                        unset($tempUser[0]);
                    }
                    foreach ($tempUser as $k => $v) {
                        $arr = $this->randArrayCoin($roundRedPackets);
                        $grabUsers[$k]['coin'] = $arr['coin'];
                        //重新组织红包数据，这个数据是删除刚刚取出那行后的新数据
                        unset($roundRedPackets[$arr['key']]);
                    }
                }
                break;
            case 2:
                # 先计算牌型的大小
                $cardList = array();
                foreach($roundRedPackets as $k=>$v){
                    $coin = strval(number_format($v['coin'], 2, '.', ''));
                    $n1 = substr($coin,-2,1); //小数点第一位
                    $n2 = substr($coin,-1);   //小数点后二位
                    $winsort_odds_key = 'n'.(($n1+$n2) % 10); // 牛几

                    // 最后是最大的牌型：牛牛
                    if((($n1+$n2) % 10)==0){
                        $winsort_odds_key = "n0";
                    }
                    # ======================================================================================================
                    $cardList[$k]['coin'] = $coin;
                    //找出对应输赢的牌型顺序
                    $cardList[$k]['winsort'] = $this->getOddsWinSort($game['odds'],'cardtype', $winsort_odds_key, 'winsort');
                    //找出对应的赔率
                    $cardList[$k]['odds'] = $this->getOddsWinSort($game['odds'],'cardtype', $winsort_odds_key, 'odds');
                    //牌型名称
                    $cardList[$k]['cardtitle'] = $this->getOddsWinSort($game['odds'],'cardtype', $winsort_odds_key, 'cardtitle');
                    # 牌型赔率代码
                    $cardList[$k]['cardtype'] = $winsort_odds_key;

                }

                # 如果有两个以上的赔率是一样的，
                # 概率用户不一定就是稳赢的玩家，
                # 有可能随机分配到已去除一个最小赔率的牌型
                # 但可以确保概率用户不会拿到最小的牌型
                $cardList = $this->sortArray($cardList, 'winsort', "ASC");

                # var_dump($cardList[array_rand($this->shuffle_assoc($cardList))]);

                $maxArrIndex = count($cardList) - 1;

                # 取出牌型中winsort这一列的最小值
                $min = $cardList[0];
                # 取出牌型中winsort这一列的最大值
                $max = $cardList[$maxArrIndex];

                if($pretreatment) {

                    # 把最小牌型的红包出列
                    unset($cardList[0]);

                    # 如果 庄家随机最大的种子值为 1 将去除最大的牌型，留给庄家
                    if($_log['bankerwon']) {
                        # 对应输赢的牌型顺序
                        $grabUsers[0]['winsort'] = $max['winsort'];
                        # 对应的赔率
                        $grabUsers[0]['odds'] = $max['odds'];
                        # 牌型名称
                        $grabUsers[0]['cardtitle'] = $max['cardtitle'];
                        # 抢到的红包金额
                        $grabUsers[0]['coin'] = $max['coin'];
                        # 牌型赔率代码
                        $grabUsers[0]['cardtype'] = $max['cardtype'];
                        # 把庄家从列表中删除
                        unset($tempUser[0]);
                        # 把最大牌型的红包删除
                        unset($cardList[$maxArrIndex]);
                    }else{
                        if(intval($game_sb_paras['grabbig']) == 0){
                            # 把最大牌型的红包删除
                            unset($cardList[$maxArrIndex]);
                        }
                    }

                    #$cardList = $this->shuffle_assoc($cardList);

                    # 先分配概率用户
                    if ($game['grabUsersTypeNumbers']['pret'] >= 1) {
                        foreach ($tempUser as $k => $v) {
                            if ($v['pointstype'] == 2) { // 概率用户
                                # 随机取一个牌型结果
                                $arrKey = array_rand($cardList,1);
                                $arr = $cardList[$arrKey];
                                unset($cardList[$arrKey]);

                                # 对应输赢的牌型顺序
                                $grabUsers[$k]['winsort'] = $arr['winsort'];
                                # 对应的赔率
                                $grabUsers[$k]['odds'] = $arr['odds'];
                                # 牌型名称
                                $grabUsers[$k]['cardtitle'] = $arr['cardtitle'];
                                # 抢到的红包金额
                                $grabUsers[$k]['coin'] = $arr['coin'];
                                # 牌型赔率代码
                                $grabUsers[$k]['cardtype'] = $arr['cardtype'];
                                //重新组织数据
                                unset($tempUser[$k]);
                            }
                        }
                    }

                    # 如果机器人有机会拿到最小的红包 或 没有正常的玩家
                    if($game_sb_paras['grabmin'] ||
                        $game['grabUsersTypeNumbers']['play'] == 0)
                    {
                        array_push($cardList, $min);
                    }
                    # 如果机器人没有有机会拿到最小的红包 且 只有一个正常的玩家 且正常玩家是庄家 且 是稳赢模式
                    if(!$game_sb_paras['grabmin'] &&
                        $game['grabUsersTypeNumbers']['play'] == 1 &&
                        $bankerUser['uid'] == $grabUsers[0]['uid'] &&
                        $_log['bankerwon'])
                    {
                        array_push($cardList, $min);
                    }
                    # 如果 概率用户没有机会拿最大 及 不是庄家稳赢 没有正常玩家 的情况下，将它加入
                    if (!$_log['bankerwon'] && !$game_sb_paras['grabbig']) {
                        array_push($cardList, $max);
                    }

                    if ($game['grabUsersTypeNumbers']['self'] >= 1) {
                        foreach ($tempUser as $k => $v) {
                            if ($v['pointstype'] == 3) { // 内部用户
                                # 随机取一个牌型结果
                                $arrKey = array_rand($cardList,1);
                                $arr = $cardList[$arrKey];
                                unset($cardList[$arrKey]);

                                # 对应输赢的牌型顺序
                                $grabUsers[$k]['winsort'] = $arr['winsort'];
                                # 对应的赔率
                                $grabUsers[$k]['odds'] = $arr['odds'];
                                # 牌型名称
                                $grabUsers[$k]['cardtitle'] = $arr['cardtitle'];
                                # 抢到的红包金额
                                $grabUsers[$k]['coin'] = $arr['coin'];
                                # 牌型赔率代码
                                $grabUsers[$k]['cardtype'] = $arr['cardtype'];
                                //重新组织数据
                                unset($tempUser[$k]);
                            }
                        }
                    }

                    # 最后分配正常玩家
                    if ($game['grabUsersTypeNumbers']['play'] >= 1) {
                        # 如果机器人没有机会拿到最小的红包
                        if(!$game_sb_paras['grabmin']) {
                            array_push($cardList, $min);
                        }
                        foreach ($tempUser as $k => $v) {
                            if ($v['pointstype'] == 1) { // 正常用户
                                # 随机取一个牌型结果
                                $arrKey = array_rand($cardList,1);
                                $arr = $cardList[$arrKey];
                                unset($cardList[$arrKey]);

                                # 对应输赢的牌型顺序
                                $grabUsers[$k]['winsort'] = $arr['winsort'];
                                # 对应的赔率
                                $grabUsers[$k]['odds'] = $arr['odds'];
                                # 牌型名称
                                $grabUsers[$k]['cardtitle'] = $arr['cardtitle'];
                                # 抢到的红包金额
                                $grabUsers[$k]['coin'] = $arr['coin'];
                                # 牌型赔率代码
                                $grabUsers[$k]['cardtype'] = $arr['cardtype'];
                                //重新组织数据
                                unset($tempUser[$k]);
                            }
                        }
                    }
                }else{
                    if($_log['bankerwon']){
                        # 对应输赢的牌型顺序
                        $grabUsers[0]['winsort'] = $max['winsort'];
                        # 对应的赔率
                        $grabUsers[0]['odds'] = $max['odds'];
                        # 牌型名称
                        $grabUsers[0]['cardtitle'] = $max['cardtitle'];
                        # 抢到的红包金额
                        $grabUsers[0]['coin'] = $max['coin'];
                        # 牌型赔率代码
                        $grabUsers[0]['cardtype'] = $max['cardtype'];
                        # 把最大牌型的红包删除 --  在数组中删除最大的牌型
                        unset($cardList[$maxArrIndex]);
                        unset($tempUser[0]);
                    }

                    # 随机分配
                    # 将数组倒序
                    $tempUser = array_reverse($tempUser,true);
                    foreach($tempUser as $k=>$v){
                        # 随机取一个牌型结果
                        $arrKey = array_rand($cardList,1);
                        $arr = $cardList[$arrKey];
                        unset($cardList[$arrKey]);

                        # 对应输赢的牌型顺序
                        $grabUsers[$k]['winsort'] = $arr['winsort'];
                        # 对应的赔率
                        $grabUsers[$k]['odds'] = $arr['odds'];
                        # 牌型名称
                        $grabUsers[$k]['cardtitle'] = $arr['cardtitle'];
                        # 抢到的红包金额
                        $grabUsers[$k]['coin'] = $arr['coin'];
                        # 牌型赔率代码
                        $grabUsers[$k]['cardtype'] = $arr['cardtype'];
                    }
                }
                # print_r($cardList);
                break;
            case 3: // 扫雷
                $mantissaCount = 0;
                # 先计算牌型的大小
                $cardList = array();
                if($game['grabUsersTypeNumbers']['play'] > 2){
                    $pretreatment = false;
                    $_log['psw']  = 0;
                    # 庄家稳赢也去除
                    $_log['bankerwon'] = 0;
                }

                # 如果指定庄家稳赢家，一定要在抢包玩家中出现一个雷
                # 重新生成直到有雷 或 重新生成了$replayLen次为止
                $replayNumbers = 1;

                $isHave = 0;
                if($pretreatment){
                    $replayLen = $game_sb_paras['slreplaylen'] ?? 1;
                }else{
                    $replayLen = 1;
                }

                if( $mantissaCount <=0){
                    # ==== End Debug info ==========
                    while($mantissaCount <= 0 && $replayNumbers <= $replayLen) {
                        //产生红包数据
                        # ==== End Debug info ==========
                        $roundRedPackets = $this->redPacketRound($redEnvelopes['coin'], $redEnvelopes['need']);
                        foreach ($roundRedPackets as $k => $v) {
                            # 当前分配到的红包的尾数
                            $coin = strval($this->formatCoin($v['coin']));
                            $current_mantissa = substr($coin, -1);   //小数点后二位
                            if ($redEnvelopes['mantissa'] == $current_mantissa) {
                                $mantissaCount++;
                                $isHave = 1;
                            }
                        }
                        $replayNumbers ++;
                    }
                    # 如果上面的数据没有产生雷，将手动重新生成红包数据
                }

                # 当庄家稳赢时，随机一个没有尾数的红包，并从红包表中删除
                $noMantissaArr = array();
                $noMantissaArrKey = -1;
                $isNoHave = 0;

                # 找出没有雷的红包
                foreach($roundRedPackets as $k=>$v){
                    $coin = strval($this->formatCoin($v['coin']));
                    $current_mantissa = substr($coin, -1);   //小数点后二位

                    if ($isNoHave == 0 && $current_mantissa != $redEnvelopes['mantissa']) {
                        $noMantissaArr['coin'] = $v['coin'];
                        $noMantissaArr['mantissa'] = $current_mantissa;
                        $noMantissaArrKey = $k;
                        $isNoHave = 1;
                        unset($roundRedPackets[$k]);
                    }
                }
                # 如果实在没有出雷就随机取一个
                if(!$isHave){
                    # 默认随机取一个
                    $arr = $this->randArrayCoin($roundRedPackets);
                    $coin = strval($this->formatCoin($arr['coin']));
                    $current_mantissa = substr($coin, -1);   //小数点后二位
                    $haveMantissaArr['coin'] = $arr['coin'];
                    $haveMantissaArr['mantissa'] = $current_mantissa;
                    $haveMantissaKey = $arr['key'];
                    unset($roundRedPackets[$arr['key']]);
                }
                //print_r($noMantissaArr);
                //}

                /*
                （1）概率用户做庄：0尾   4个机器人闲家，固定1到2个抢到0尾。   概率用户做闲：0尾  概率用户不会抢到0尾，其余的机器人随机
                （2）普通用户做庄：0尾   4个机器人闲家，全都不会抢到0尾。   普通用户做闲：0尾   普通用户一定抢到0尾，其余的机器人随机
                （3）当有2个用户，1普1概时：概率用户做庄，普闲家必中雷，其余随机 。
                （4）概率用户做闲，普通用户也做闲，机器做庄，概率用户不中雷，普通用户必中。
                （5）概率用户做闲，普通用户做庄，闲家全部不中雷。
                （6）当普通用户大于2个以上，概率随机
                */

                # 2018-11-07 当普通用户大于2个以上，概率随机



                if($pretreatment){

                    $_log['psw']  = 1;
                    # 庄家稳赢也去除
                    $_log['bankerwon'] = 0;
                    # ------------------------- 原来的分配规则 ---  BEGIN   --------
                    /*
                    # 最后分配正常玩家
                    if ($game['grabUsersTypeNumbers']['play'] >= 1) {
                        foreach ($tempUser as $k => $v) {
                            if ($v['pointstype'] == 1) { // 正常用户

                                # 随机取一个牌型结果
                                $arr = $this->randArrayCoin($roundRedPackets);
                                $coin = strval($this->formatCoin($arr['coin']));
                                $current_mantissa = substr($coin, -1);   //小数点后二位
                                $arr['mantissa'] = $current_mantissa;
                                unset($roundRedPackets[$arr['key']]);

                                $grabUsers[$k]['mantissa'] = $arr['mantissa'];
                                $grabUsers[$k]['coin'] = $arr['coin'];

                                //重新组织数据
                                unset($tempUser[$k]);
                            }
                        }
                    }
                    # 然后分配内部用户
                    if ($game['grabUsersTypeNumbers']['self'] >= 1) {
                        foreach ($tempUser as $k => $v) {
                            if ($v['pointstype'] == 3) { // 内部用户

                                # 随机取一个牌型结果
                                $arr = $this->randArrayCoin($roundRedPackets);
                                $coin = strval($this->formatCoin($arr['coin']));
                                $current_mantissa = substr($coin, -1);   //小数点后二位
                                $arr['mantissa'] = $current_mantissa;
                                unset($roundRedPackets[$arr['key']]);

                                $grabUsers[$k]['mantissa'] = $arr['mantissa'];
                                $grabUsers[$k]['coin'] = $arr['coin'];
                                unset($tempUser[$k]);
                            }
                        }
                    }
                    # 概率用户可能要后面计算，因为雷有可能会出现多次，在前面分配的玩家可能就比较有机会分配到
                    # 先分配概率用户
                    if ($game['grabUsersTypeNumbers']['pret'] >= 1) {
                        foreach ($tempUser as $k => $v) {
                            if ($v['pointstype'] == 2) { // 概率用户

                                # 随机取一个牌型结果
                                $arr = $this->randArrayCoin($roundRedPackets);
                                $coin = strval($this->formatCoin($arr['coin']));
                                $current_mantissa = substr($coin, -1);   //小数点后二位
                                $arr['mantissa'] = $current_mantissa;
                                unset($roundRedPackets[$arr['key']]);

                                $grabUsers[$k]['mantissa'] = $arr['mantissa'];
                                $grabUsers[$k]['coin'] = $arr['coin'];
                                unset($tempUser[$k]);
                            }
                        }
                    }
                    */
                    # ------------------------- 原来的分配规则 ---  END   --------

                    # ------------------------- 2018-11-07 分配规则 ---  BEGIN   --------
                    /*
                    （1）概率用户做庄：0尾   4个机器人闲家，固定1到2个抢到0尾。   概率用户做闲：0尾  概率用户不会抢到0尾，其余的机器人随机
                    （2）普通用户做庄：0尾   4个机器人闲家，全都不会抢到0尾。   普通用户做闲：0尾   普通用户一定抢到0尾，其余的机器人随机
                    （3）- 当有2个用户，1普1概时：概率用户做庄，普闲家必中雷，其余随机 。
                    （4）概率用户做闲，普通用户也做闲，机器做庄，概率用户不中雷，普通用户必中。
                    （5）概率用户做闲，普通用户做庄，闲家全部不中雷。
                    （6）当普通用户大于2个以上，概率随机
                    */

                    # 找出 有雷 的红包金额位置
                    //print_r($roundRedPackets);
                    //foreach ($roundRedPackets as $k=>$v){
                    if( $isHave ){
                        foreach($roundRedPackets as $k=>$v){
                            $coin = strval($this->formatCoin($v['coin']));
                            $current_mantissa = substr($coin, -1);   //小数点后二位
                            if ($current_mantissa == $redEnvelopes['mantissa']) {
                                $haveMantissaKey = $k;
                                //$haveMantissaArr = $v;
                                $haveMantissaArr['mantissa'] = $current_mantissa;
                                $haveMantissaArr['coin'] = $coin;
                                unset($roundRedPackets[$k]);
                                break;
                            }
                        }
                    }

                    //}

                    $isFP = 0; // 普通用户分配标识，防止有多个普通用户多次分配一个雷

                    # region 概率用户做庄
                    if($grabUsers[0]['pointstype'] == 2){

                        # 分配没有雷的红包给概率用户（庄家）
                        $grabUsers[0]['coin'] = $noMantissaArr['coin'];
                        $grabUsers[0]['mantissa'] = $noMantissaArr['mantissa'];
                        unset($roundRedPackets[$noMantissaArrKey]);
                        unset($tempUser[0]);

                        # 如果其它都是机器人就随机分配
                        if($game['grabUsersTypeNumbers']['self'] >= ($redEnvelopes['need']-1)){
                            if($haveMantissaKey >= 0) {
                                # 加入有雷的红包到红包列表中
                                array_push($roundRedPackets, $haveMantissaArr);
                            }
                            foreach ($tempUser as $uk=>$uv) {
                                # 随机分配红包
                                $arr = $this->randArrayCoin($roundRedPackets);
                                $coin = strval($this->formatCoin($arr['coin']));
                                $current_mantissa = substr($coin, -1);   //小数点后二位
                                $grabUsers[$uk]['coin'] = $arr['coin'];
                                $grabUsers[$uk]['mantissa'] = $current_mantissa;
                                unset($roundRedPackets[$arr['key']]);
                            }
                            # 如果机器人的数量不是 need -1
                        }else{
                            # region 1 - 如果有一个普通用户，它一定中雷
                            if($game['grabUsersTypeNumbers']['play'] == 1){
                                # region 找出这个普通用户,把这个雷直接给它，其它的用户就随机即可
                                foreach ($tempUser as $uk=>$uv) {
                                    if ($uv['pointstype'] == 1 && $isFP ==0 && $haveMantissaKey >= 0) { // 正常用户 且 有出雷
                                        $arr = $haveMantissaArr; //$roundRedPackets[$haveMantissaKey];
                                        $coin = strval($this->formatCoin($arr['coin']));
                                        $current_mantissa = substr($coin, -1);   //小数点后二位
                                        $grabUsers[$uk]['coin'] = $arr['coin'];
                                        $grabUsers[$uk]['mantissa'] = $current_mantissa;
                                        $isFP = 1;
                                    }else{
                                        # 随机分配红包
                                        $arr = $this->randArrayCoin($roundRedPackets);
                                        $coin = strval($this->formatCoin($arr['coin']));
                                        $current_mantissa = substr($coin, -1);   //小数点后二位
                                        $grabUsers[$uk]['coin'] = $arr['coin'];
                                        $grabUsers[$uk]['mantissa'] = $current_mantissa;
                                        unset($roundRedPackets[$arr['key']]);
                                    }
                                }
                                # endregion
                            }else{
                                # region 如果普通用户大于等于2时就随机分配红包
                                if($haveMantissaKey >= 0) {
                                    # 加入有雷的红包到红包列表中
                                    array_push($roundRedPackets, $haveMantissaArr);
                                }
                                foreach ($tempUser as $uk=>$uv) {
                                    # 随机分配红包
                                    $arr = $this->randArrayCoin($roundRedPackets);
                                    $coin = strval($this->formatCoin($arr['coin']));
                                    $current_mantissa = substr($coin, -1);   //小数点后二位
                                    $grabUsers[$uk]['coin'] = $arr['coin'];
                                    $grabUsers[$uk]['mantissa'] = $current_mantissa;
                                    unset($roundRedPackets[$arr['key']]);
                                }
                                # endregion
                            }
                        }
                        # endregion
                    }
                    # endregion

                    # region 普通用户做庄
                    if($grabUsers[0]['pointstype'] == 1) {
                        # 如果除了庄家其它都是机器人
                        if ($game['grabUsersTypeNumbers']['self'] >= ($redEnvelopes['need'] - 1)) {
                            # 分配有雷的红包给庄家（普通用户）
                            if ($haveMantissaKey != -1) { // 有出雷
                                $arr = $haveMantissaArr; //$roundRedPackets[$haveMantissaKey];
                                $coin = strval($this->formatCoin($arr['coin']));
                                unset($tempUser[0]);
                            } else {
                                # 随机分配红包
                                $arr = $this->randArrayCoin($roundRedPackets);
                                $coin = strval($this->formatCoin($arr['coin']));
                                unset($roundRedPackets[$arr['key']]);
                                unset($tempUser[0]);
                            }
                            $current_mantissa = substr($coin, -1);   //小数点后二位
                            $grabUsers[0]['coin'] = $arr['coin'];
                            $grabUsers[0]['mantissa'] = $current_mantissa;

                            if ($noMantissaArrKey >= 0) {
                                # 加入没有雷的红包到红包列表中
                                $roundRedPackets[] = $noMantissaArr;
                            }

                            foreach ($tempUser as $uk => $uv) {
                                # 随机分配红包
                                $arr = $this->randArrayCoin($roundRedPackets);
                                $coin = strval($this->formatCoin($arr['coin']));
                                $current_mantissa = substr($coin, -1);   //小数点后二位
                                $grabUsers[$uk]['coin'] = $arr['coin'];
                                $grabUsers[$uk]['mantissa'] = $current_mantissa;
                                unset($roundRedPackets[$arr['key']]);
                            }
                        } elseif ($game['grabUsersTypeNumbers']['play'] >= 2) {
                            # 庄家不拿有雷的红包，给其它闲家拿
                            $grabUsers[0]['coin'] = $noMantissaArr['coin'];
                            $grabUsers[0]['mantissa'] = $noMantissaArr['mantissa'];
                            unset($tempUser[0]);

                            foreach ($tempUser as $uk => $uv) {
                                if ($isFP == 0 && $uv['pointstype'] == 1) {
                                    if ($haveMantissaKey != -1) { // 有出雷
                                        $arr = $haveMantissaArr;
                                        $coin = strval($this->formatCoin($arr['coin']));
                                    } else {
                                        # 随机分配红包
                                        $arr = $this->randArrayCoin($roundRedPackets);
                                        $coin = strval($this->formatCoin($arr['coin']));
                                        unset($roundRedPackets[$arr['key']]);
                                    }
                                    $current_mantissa = substr($coin, -1);   //小数点后二位
                                    $grabUsers[$uk]['coin'] = $arr['coin'];
                                    $grabUsers[$uk]['mantissa'] = $current_mantissa;
                                    $isFP = 1;
                                } else {
                                    # 随机分配红包
                                    $arr = $this->randArrayCoin($roundRedPackets);
                                    $coin = strval($this->formatCoin($arr['coin']));
                                    $current_mantissa = substr($coin, -1);   //小数点后二位
                                    $grabUsers[$uk]['coin'] = $arr['coin'];
                                    $grabUsers[$uk]['mantissa'] = $current_mantissa;
                                    unset($roundRedPackets[$arr['key']]);
                                }
                            }
                        } else {
                            # 庄家拿有雷的红包，给其它闲家拿
                            $grabUsers[0]['coin'] = $haveMantissaArr['coin'];
                            $grabUsers[0]['mantissa'] = $haveMantissaArr['mantissa'];
                            unset($tempUser[0]);

                            if ($noMantissaArrKey >= 0) {
                                # 加入有雷的红包到红包列表中
                                $roundRedPackets[] = $noMantissaArr;
                            }

                            foreach ($tempUser as $uk => $uv) {
                                # 随机分配红包
                                $arr = $this->randArrayCoin($roundRedPackets);
                                $coin = strval($this->formatCoin($arr['coin']));
                                $current_mantissa = substr($coin, -1);   //小数点后二位
                                $grabUsers[$uk]['coin'] = $arr['coin'];
                                $grabUsers[$uk]['mantissa'] = $current_mantissa;
                                unset($roundRedPackets[$arr['key']]);

                            }
                        }
                    }
                    # endregion

                    # region 内部用户做庄
                    //print_r($grabUsers[0]['issue']);

                    if($grabUsers[0]['pointstype'] == 3) {
                        $isGivePret = 0;

                        //print_r($game['grabUsersTypeNumbers']);
                        # 1 - 如果除了庄家其它都不是机器人
                        if ($game['grabUsersTypeNumbers']['play'] >= 1) {
                            # 庄家不拿有雷的红包，给其它闲家拿
                            $grabUsers[0]['coin'] = $noMantissaArr['coin'];
                            $grabUsers[0]['mantissa'] = $noMantissaArr['mantissa'];
                            unset($roundRedPackets[$noMantissaArrKey]);
                            unset($tempUser[0]);
                            foreach ($tempUser as $uk => $uv) {
                                if ($isFP == 0 && $uv['pointstype'] == 1) {

                                    $arr = $haveMantissaArr;
                                    $coin = strval($this->formatCoin($arr['coin']));
                                    $current_mantissa = substr($coin, -1);   //小数点后二位
                                    $grabUsers[$uk]['coin'] = $arr['coin'];
                                    $grabUsers[$uk]['mantissa'] = $current_mantissa;
                                    $isFP = 1;
                                } else {
                                    # 随机分配红包
                                    $arr = $this->randArrayCoin($roundRedPackets);
                                    $coin = strval($this->formatCoin($arr['coin']));
                                    $current_mantissa = substr($coin, -1);   //小数点后二位
                                    $grabUsers[$uk]['coin'] = $arr['coin'];
                                    $grabUsers[$uk]['mantissa'] = $current_mantissa;
                                    unset($roundRedPackets[$arr['key']]);
                                }
                            }
                        }elseif ( $game['grabUsersTypeNumbers']['pret'] >= 1 ){

                            if ($haveMantissaKey >= 0) {
                                # 加入有雷的红包到红包列表中
                                $roundRedPackets[] = $haveMantissaArr;
                            }
                            foreach ($tempUser as $uk => $uv) {
                                if ( $isGivePret == 0 && $uv['pointstype'] == 2) {
                                    $grabUsers[$uk]['coin'] = $noMantissaArr['coin'];
                                    $grabUsers[$uk]['mantissa'] = $noMantissaArr['mantissa'];
                                    unset($roundRedPackets[$noMantissaArrKey]);
                                    unset($tempUser[$uk]);
                                    $isGivePret = 1;
                                }else{
                                    # 随机分配红包
                                    $arr = $this->randArrayCoin($roundRedPackets);
                                    $coin = strval($this->formatCoin($arr['coin']));
                                    $current_mantissa = substr($coin, -1);   //小数点后二位
                                    $grabUsers[$uk]['coin'] = $arr['coin'];
                                    $grabUsers[$uk]['mantissa'] = $current_mantissa;
                                    unset($roundRedPackets[$arr['key']]);
                                }
                            }

                        }else {
                            # 庄家不拿有雷的红包，给其它闲家拿
                            $grabUsers[0]['coin'] = $noMantissaArr['coin'];
                            $grabUsers[0]['mantissa'] = $noMantissaArr['mantissa'];
                            unset($roundRedPackets[$noMantissaArrKey]);
                            unset($tempUser[0]);
                            if ($haveMantissaKey >= 0) {
                                # 加入有雷的红包到红包列表中
                                $roundRedPackets[] = $haveMantissaArr;
                            }
                            //print_r($roundRedPackets);
                            foreach ($tempUser as $uk => $uv) {
                                # 随机分配红包
                                $arr = $this->randArrayCoin($roundRedPackets);
                                $coin = strval($this->formatCoin($arr['coin']));
                                $current_mantissa = substr($coin, -1);   //小数点后二位
                                $grabUsers[$uk]['coin'] = $arr['coin'];
                                $grabUsers[$uk]['mantissa'] = $current_mantissa;
                                unset($roundRedPackets[$arr['key']]);

                            }
                        }
                    }
                    # endregion


                    # ------------------------- 2018-11-07 分配规则 ---  END   ----------
                }else{
                    if($_log['bankerwon']){
                        $grabUsers[0]['coin'] = $noMantissaArr['coin'];
                        $grabUsers[0]['mantissa'] = $noMantissaArr['mantissa'];
                        unset($tempUser[0]);
                    }else{
                        if($noMantissaArrKey >= 0){
                            array_push($roundRedPackets, $noMantissaArr);
                        }
                    }
                    if( isset($haveMantissaArr) && !empty($haveMantissaArr) ){
                        array_push($roundRedPackets, $haveMantissaArr);
                    }
                    # 分配红包
                    foreach ($tempUser as $uk=>$uv) {
                        # 随机分配红包
                        $arr = $this->randArrayCoin($roundRedPackets);
                        $coin = strval($this->formatCoin($arr['coin']));
                        $current_mantissa = substr($coin, -1);   //小数点后二位
                        $grabUsers[$uk]['coin'] = $arr['coin'];
                        $grabUsers[$uk]['mantissa'] = $current_mantissa;
                        unset($roundRedPackets[$arr['key']]);
                    }
                }
                break;

            # ---------------------------------------- 二八杠 预算过程 --------------------------------------------------
            case 4:
                # 先计算牌型的大小
                $cardList = array();
                foreach($roundRedPackets as $k=>$v){
                    $coin = strval(number_format($v['coin'], 2, '.', ''));

                    $n1 = substr($coin,-2,1); //小数点第一位
                    $n2 = substr($coin,-1);   //小数点后二位

                    # region 匹配设置好的红包牌型
                    $n1n2 = $n1 . $n2;

                    $cardtype_number = (($n1+$n2) % 10);
                    $winsort_odds_key = 'd0'; // 0点

                    # 白板+X点
                    if($n1=='0'){
                        $winsort_odds_key = 'b0d' . $n2;
                    }else{
                        # 点数
                        if(($n1+$n2) > 0){
                            $winsort_odds_key = 'd' . $cardtype_number;
                        }
                    }
                    # 二八杠
                    if($n1n2=='28'){
                        $winsort_odds_key = 'ebg28';
                    }
                    # 对子
                    if($n1 == $n2){
                        $winsort_odds_key = 'dz' . $n1;
                    }
                    # 对白板
                    if($n1n2=='00'){
                        $winsort_odds_key = 'd00';
                    }
                    # ======================================================================================================
                    $cardList[$k]['coin'] = $coin;
                    //找出对应输赢的牌型顺序
                    $cardList[$k]['winsort'] = $this->getOddsWinSort($game['odds'],'cardtype', $winsort_odds_key, 'winsort');
                    //找出对应的赔率
                    $cardList[$k]['odds'] = $this->getOddsWinSort($game['odds'],'cardtype', $winsort_odds_key, 'odds');
                    //牌型名称
                    $cardList[$k]['cardtitle'] = $this->getOddsWinSort($game['odds'],'cardtype', $winsort_odds_key, 'cardtitle');
                    # 牌型赔率代码
                    $cardList[$k]['cardtype'] = $winsort_odds_key;

                }

                # 如果有两个以上的赔率是一样的，
                # 概率用户不一定就是稳赢的玩家，
                # 有可能随机分配到已去除一个最小赔率的牌型
                # 但可以确保概率用户不会拿到最小的牌型
                $cardList = $this->sortArray($cardList, 'winsort', "ASC");

                $middenArr = $cardList;
                $maxArrIndex = count($cardList) - 1;

                # 取出牌型中winsort这一列的最小值
                $min = $middenArr[0];
                # 取出牌型中winsort这一列的最大值
                $max = $middenArr[$maxArrIndex];


                if($pretreatment) {
                    //提出最小的牌型
                    unset($cardList[0]);

                    # 如果 庄家随机最大的种子值为 1 将去除最大的牌型，留给庄家。庄家稳赢
                    if($_log['bankerwon']) {
                        # 对应输赢的牌型顺序
                        $grabUsers[0]['winsort'] = $max['winsort'];
                        # 对应的赔率
                        $grabUsers[0]['odds'] = $max['odds'];
                        # 牌型名称
                        $grabUsers[0]['cardtitle'] = $max['cardtitle'];
                        # 抢到的红包金额
                        $grabUsers[0]['coin'] = $max['coin'];
                        # 牌型赔率代码
                        $grabUsers[0]['cardtype'] = $max['cardtype'];
                        # 把庄家从列表中删除
                        unset($tempUser[0]);
                        # 把最大牌型的红包删除 --  在数组中删除最大的牌型
                        unset($cardList[$maxArrIndex]);
                    }else{
                        if(intval($game_sb_paras['grabbig']) == 0){
                            # 把最大牌型的红包删除
                            unset($cardList[$maxArrIndex]);
                        }
                    }

                    $cardList = $this->shuffle_assoc($cardList);

                    # 先分配概率用户
                    if ($game['grabUsersTypeNumbers']['pret'] >= 1) {
                        foreach ($tempUser as $k => $v) {
                            if ($v['pointstype'] == 2) { // 概率用户

                                # 随机取一个牌型结果
                                $arrKey = array_rand($cardList,1);
                                $arr = $cardList[$arrKey];
                                unset($cardList[$arrKey]);

                                # 对应输赢的牌型顺序
                                $grabUsers[$k]['winsort'] = $arr['winsort'];
                                # 对应的赔率
                                $grabUsers[$k]['odds'] = $arr['odds'];
                                # 牌型名称
                                $grabUsers[$k]['cardtitle'] = $arr['cardtitle'];
                                # 抢到的红包金额
                                $grabUsers[$k]['coin'] = $arr['coin'];
                                # 牌型赔率代码
                                $grabUsers[$k]['cardtype'] = $arr['cardtype'];
                                //重新组织数据
                                unset($tempUser[$k]);
                            }
                        }
                    }
                    # 如果机器人有机会拿到最小的红包 或 没有正常的玩家
                    if($game_sb_paras['grabmin'] ||
                        $game['grabUsersTypeNumbers']['play'] == 0)
                    {
                        array_push($cardList, $min);
                    }
                    # 如果机器人没有有机会拿到最小的红包 且 只有一个正常的玩家 且正常玩家是庄家 且 是稳赢模式
                    if(!$game_sb_paras['grabmin'] &&
                        $game['grabUsersTypeNumbers']['play'] == 1 &&
                        $bankerUser['uid'] == $grabUsers[0]['uid'] &&
                        $_log['bankerwon'])
                    {
                        array_push($cardList, $min);
                    }
                    # 如果 概率用户没有机会拿最大 及 不是庄家稳赢 没有正常玩家 的情况下，将它加入
                    if (!$_log['bankerwon'] && !$game_sb_paras['grabbig']) {
                        array_push($cardList, $max);
                    }

                    if ($game['grabUsersTypeNumbers']['self'] >= 1) {
                        foreach ($tempUser as $k => $v) {
                            if ($v['pointstype'] == 3 && count($cardList) > 0) { // 内部用户
                                # 随机取一个牌型结果
                                $arrKey = array_rand($cardList,1);
                                $arr = $cardList[$arrKey];
                                unset($cardList[$arrKey]);

                                # 对应输赢的牌型顺序
                                $grabUsers[$k]['winsort'] = $arr['winsort'];
                                # 对应的赔率
                                $grabUsers[$k]['odds'] = $arr['odds'];
                                # 牌型名称
                                $grabUsers[$k]['cardtitle'] = $arr['cardtitle'];
                                # 抢到的红包金额
                                $grabUsers[$k]['coin'] = $arr['coin'];
                                # 牌型赔率代码
                                $grabUsers[$k]['cardtype'] = $arr['cardtype'];
                                //重新组织数据
                                unset($tempUser[$k]);
                            }
                        }
                    }

                    # 最后分配正常玩家
                    if ($game['grabUsersTypeNumbers']['play'] >= 1) {
                        # 如果机器人没有机会拿到最小的红包
                        if(!$game_sb_paras['grabmin']) {
                            array_push($cardList, $min);
                        }
                        foreach ($tempUser as $k => $v) {
                            if ($v['pointstype'] == 1) { // 正常用户

                                # 随机取一个牌型结果
                                $arrKey = array_rand($cardList,1);
                                $arr = $cardList[$arrKey];
                                unset($cardList[$arrKey]);

                                # 对应输赢的牌型顺序
                                $grabUsers[$k]['winsort'] = $arr['winsort'];
                                # 对应的赔率
                                $grabUsers[$k]['odds'] = $arr['odds'];
                                # 牌型名称
                                $grabUsers[$k]['cardtitle'] = $arr['cardtitle'];
                                # 抢到的红包金额
                                $grabUsers[$k]['coin'] = $arr['coin'];
                                # 牌型赔率代码
                                $grabUsers[$k]['cardtype'] = $arr['cardtype'];
                                //重新组织数据
                                unset($tempUser[$k]);
                            }
                        }
                    }
                }else{
                    # 如果庄家是随机指定为最大
                    if($_log['bankerwon']) {
                        # 对应输赢的牌型顺序
                        $grabUsers[0]['winsort'] = $max['winsort'];
                        # 对应的赔率
                        $grabUsers[0]['odds'] = $max['odds'];
                        # 牌型名称
                        $grabUsers[0]['cardtitle'] = $max['cardtitle'];
                        # 抢到的红包金额
                        $grabUsers[0]['coin'] = $max['coin'];
                        # 牌型赔率代码
                        $grabUsers[0]['cardtype'] = $max['cardtype'];
                        # 把最大牌型的红包删除 --  在数组中删除最大的牌型
                        unset($cardList[$maxArrIndex]);
                        unset($tempUser[0]);
                    }
                    # 将数组倒序
                    $tempUser = array_reverse($tempUser,true);

                    foreach($tempUser as $k=>$v){
                        # 随机取一个牌型结果
                        $arrKey = array_rand($cardList);
                        $arr = $cardList[$arrKey];
                        unset($cardList[$arrKey]);

                        # 对应输赢的牌型顺序
                        $grabUsers[$k]['winsort'] = $arr['winsort'];
                        # 对应的赔率
                        $grabUsers[$k]['odds'] = $arr['odds'];
                        # 牌型名称
                        $grabUsers[$k]['cardtitle'] = $arr['cardtitle'];
                        # 抢到的红包金额
                        $grabUsers[$k]['coin'] = $arr['coin'];
                        # 牌型赔率代码
                        $grabUsers[$k]['cardtype'] = $arr['cardtype'];
                    }
                }
                break;
            # ---------------------------------------------------------------------------------------------------------
            case 5:
                # 先计算牌型的大小
                $cardList = array();
                foreach($roundRedPackets as $k=>$v){
                    $coin = strval(number_format($v['coin'], 2, '.', ''));
                    $n1 = substr($coin,-2,1); //小数点第一位
                    $n2 = substr($coin,-1);   //小数点后二位

                    $winsort_odds_key = 'n'.(($n1+$n2) % 10); // 牛几

                    // 最后是最大的牌型：牛牛
                    if((($n1+$n2) % 10)==0){
                        $winsort_odds_key = "n0";
                    }
                    # ======================================================================================================
                    $cardList[$k]['coin'] = $coin;
                    //找出对应输赢的牌型顺序
                    $cardList[$k]['winsort'] = $this->getOddsWinSort($game['odds'],'cardtype', $winsort_odds_key, 'winsort');
                    //找出对应的赔率
                    $cardList[$k]['odds'] = $this->getOddsWinSort($game['odds'],'cardtype', $winsort_odds_key, 'odds');
                    //牌型名称
                    $cardList[$k]['cardtitle'] = $this->getOddsWinSort($game['odds'],'cardtype', $winsort_odds_key, 'cardtitle');
                    # 牌型赔率代码
                    $cardList[$k]['cardtype'] = $winsort_odds_key;

                }

                # 如果有两个以上的赔率是一样的，
                # 概率用户不一定就是稳赢的玩家，
                # 有可能随机分配到已去除一个最小赔率的牌型
                # 但可以确保概率用户不会拿到最小的牌型
                $cardList = $this->sortArray($cardList, 'winsort', "ASC");

                $middenArr = $cardList;
                $maxArrIndex = count($cardList) - 1;

                # 取出牌型中winsort这一列的最小值
                $min = $middenArr[0];
                # 取出牌型中winsort这一列的最大值
                $max = $middenArr[$maxArrIndex];


                if($pretreatment) {

                    unset($cardList[0]);


                    # 如果 庄家随机最大的种子值为 1 将去除最大的牌型，留给庄家
                    if($_log['bankerwon']) {
                        # 对应输赢的牌型顺序
                        $grabUsers[0]['winsort'] = $max['winsort'];
                        # 对应的赔率
                        $grabUsers[0]['odds'] = $max['odds'];
                        # 牌型名称
                        $grabUsers[0]['cardtitle'] = $max['cardtitle'];
                        # 抢到的红包金额
                        $grabUsers[0]['coin'] = $max['coin'];
                        # 牌型赔率代码
                        $grabUsers[0]['cardtype'] = $max['cardtype'];
                        # 把庄家从列表中删除
                        unset($tempUser[0]);
                        # 把最大牌型的红包删除 --  在数组中删除最大的牌型
                        unset($cardList[$maxArrIndex]);
                    }else{
                        if(intval($game_sb_paras['grabbig']) == 0){
                            # 把最大牌型的红包删除
                            unset($cardList[$maxArrIndex]);
                        }
                    }

                    $cardList = $this->shuffle_assoc($cardList);
                    # 先分配概率用户
                    if ($game['grabUsersTypeNumbers']['pret'] >= 1) {
                        foreach ($tempUser as $k => $v) {
                            if ($v['pointstype'] == 2) { // 概率用户

                                # 随机取一个牌型结果
                                $arrKey = array_rand($cardList,1);
                                $arr = $cardList[$arrKey];
                                unset($cardList[$arrKey]);

                                # 对应输赢的牌型顺序
                                $grabUsers[$k]['winsort'] = $arr['winsort'];
                                # 对应的赔率
                                $grabUsers[$k]['odds'] = $arr['odds'];
                                # 牌型名称
                                $grabUsers[$k]['cardtitle'] = $arr['cardtitle'];
                                # 抢到的红包金额
                                $grabUsers[$k]['coin'] = $arr['coin'];
                                # 牌型赔率代码
                                $grabUsers[$k]['cardtype'] = $arr['cardtype'];
                                //重新组织数据
                                unset($tempUser[$k]);
                            }
                        }
                    }
                    # 如果机器人有机会拿到最小的红包 或 没有正常的玩家
                    if($game_sb_paras['grabmin'] ||
                        $game['grabUsersTypeNumbers']['play'] == 0)
                    {
                        array_push($cardList, $min);
                    }
                    # 如果机器人没有有机会拿到最小的红包 且 只有一个正常的玩家 且正常玩家是庄家 且 是稳赢模式
                    if(!$game_sb_paras['grabmin'] &&
                        $game['grabUsersTypeNumbers']['play'] == 1 &&
                        $bankerUser['uid'] == $grabUsers[0]['uid'] &&
                        $_log['bankerwon'])
                    {
                        array_push($cardList, $min);
                    }
                    # 如果 概率用户没有机会拿最大 及 不是庄家稳赢 没有正常玩家 的情况下，将它加入
                    if (!$_log['bankerwon'] && !$game_sb_paras['grabbig']) {
                        array_push($cardList, $max);
                    }
                    if ($game['grabUsersTypeNumbers']['self'] >= 1) {
                        $cardList = $this->shuffle_assoc($cardList);
                        foreach ($tempUser as $k => $v) {
                            if ($v['pointstype'] == 3 && count($cardList ) > 0) { // 内部用户

                                # 随机取一个牌型结果
                                $arrKey = array_rand($cardList, 1);
                                $arr = $cardList[$arrKey];
                                unset($cardList[$arrKey]);

                                # 对应输赢的牌型顺序
                                $grabUsers[$k]['winsort'] = $arr['winsort'];
                                # 对应的赔率
                                $grabUsers[$k]['odds'] = $arr['odds'];
                                # 牌型名称
                                $grabUsers[$k]['cardtitle'] = $arr['cardtitle'];
                                # 抢到的红包金额
                                $grabUsers[$k]['coin'] = $arr['coin'];
                                # 牌型赔率代码
                                $grabUsers[$k]['cardtype'] = $arr['cardtype'];
                                //重新组织数据
                                unset($tempUser[$k]);
                            }
                        }
                    }

                    # 最后分配正常玩家
                    if ($game['grabUsersTypeNumbers']['play'] >= 1) {
                        # 如果机器人没有机会拿到最小的红包
                        if(!$game_sb_paras['grabmin']) {
                            array_push($cardList, $min);
                        }
                        foreach ($tempUser as $k => $v) {
                            if ($v['pointstype'] == 1  && count($cardList ) > 0) { // 正常用户

                                # 随机取一个牌型结果
                                $arrKey = array_rand($cardList, 1);
                                $arr = $cardList[$arrKey];
                                unset($cardList[$arrKey]);

                                # 对应输赢的牌型顺序
                                $grabUsers[$k]['winsort'] = $arr['winsort'];
                                # 对应的赔率
                                $grabUsers[$k]['odds'] = $arr['odds'];
                                # 牌型名称
                                $grabUsers[$k]['cardtitle'] = $arr['cardtitle'];
                                # 抢到的红包金额
                                $grabUsers[$k]['coin'] = $arr['coin'];
                                # 牌型赔率代码
                                $grabUsers[$k]['cardtype'] = $arr['cardtype'];
                                //重新组织数据
                                unset($tempUser[$k]);
                            }
                        }
                    }
                }else{
                    # 如果庄家是随机指定为最大
                    if($_log['bankerwon']) {
                        # 对应输赢的牌型顺序
                        $grabUsers[0]['winsort'] = $max['winsort'];
                        # 对应的赔率
                        $grabUsers[0]['odds'] = $max['odds'];
                        # 牌型名称
                        $grabUsers[0]['cardtitle'] = $max['cardtitle'];
                        # 抢到的红包金额
                        $grabUsers[0]['coin'] = $max['coin'];
                        # 牌型赔率代码
                        $grabUsers[0]['cardtype'] = $max['cardtype'];
                        # 把最大牌型的红包删除 --  在数组中删除最大的牌型
                        unset($cardList[$maxArrIndex]);
                        unset($tempUser[0]);
                    }
                    # 将数组倒序
                    $tempUser = array_reverse($tempUser,true);
                    foreach ($tempUser as $k=>$v){
                        # 随机取一个牌型结果
                        $arrKey = array_rand($cardList, 1);
                        $arr = $cardList[$arrKey];

                        # 对应输赢的牌型顺序
                        $grabUsers[$k]['winsort'] = $arr['winsort'];
                        # 对应的赔率
                        $grabUsers[$k]['odds'] = $arr['odds'];
                        # 牌型名称
                        $grabUsers[$k]['cardtitle'] = $arr['cardtitle'];
                        # 抢到的红包金额
                        $grabUsers[$k]['coin'] = $arr['coin'];
                        # 牌型赔率代码
                        $grabUsers[$k]['cardtype'] = $arr['cardtype'];

                        unset($cardList[$arrKey]);
                    }
                    # 再把数组倒序回来

                }
                break;
        }

        $this->db->insert(\Config\Sys::$dbprefix.'probability_log')->cols($_log)->query();

        return $grabUsers;
    }

    # endregion

    # region 只保留中文字符
    public static function onlyZH($str)
    {
        //转换 GB2312 -> UTF-8
        $str = mb_convert_encoding($str, 'UTF-8', 'GB2312');
        preg_match_all('/[\x{4e00}-\x{9fff}]+/u', $str, $matches);
        $str = join('', $matches[0]);
        //转换 UTF-8 -> GB2312
        $str = mb_convert_encoding($str, 'GB2312', 'UTF-8');
        return $str; //输出 中文字符
    }

    # region 随机房间名称
    public function roundRoomName()
    {
        $nicheng_tou= [
            '快乐的','冷静的','醉熏的','潇洒的','糊涂的','积极的','冷酷的','深情的','粗暴的','温柔的',
            '可爱的','愉快的','义气的','认真的','威武的','帅气的','传统的','潇洒的','漂亮的','自然的',
            '专一的','听话的','昏睡的','狂野的','等待的','搞怪的','幽默的','魁梧的','活泼的','开心的',
            '高兴的','超帅的','留胡子的','坦率的','直率的','轻松的','痴情的','完美的','精明的','无聊的',
            '有魅力的','丰富的','繁荣的','饱满的','炙热的','暴躁的','碧蓝的','俊逸的','英勇的','健忘的',
            '故意的','无心的','土豪的','朴实的','兴奋的','幸福的','淡定的','不安的','阔达的','孤独的',
            '独特的','疯狂的','时尚的','落后的','风趣的','忧伤的','大胆的','爱笑的','矮小的','健康的',
            '合适的','玩命的','沉默的','斯文的','香蕉','苹果','鲤鱼','鳗鱼','任性的','细心的','粗心的',
            '大意的','甜甜的','酷酷的','健壮的','英俊的','霸气的','阳光的','默默的','大力的','孝顺的',
            '忧虑的','着急的','紧张的','善良的','凶狠的','害怕的','重要的','危机的','欢喜的','欣慰的',
            '满意的','跳跃的','诚心的','称心的','如意的','怡然的','娇气的','无奈的','无语的','激动的',
            '愤怒的','美好的','感动的','激情的','激昂的','震动的','虚拟的','超级的','寒冷的','精明的',
            '明理的','犹豫的','忧郁的','寂寞的','奋斗的','勤奋的','现代的','过时的','稳重的','热情的',
            '含蓄的','开放的','无辜的','多情的','纯真的','拉长的','热心的','从容的','体贴的','风中的',
            '曾经的','追寻的','儒雅的','优雅的','开朗的','外向的','内向的','清爽的','文艺的','长情的',
            '平常的','单身的','伶俐的','高大的','懦弱的','柔弱的','爱笑的','乐观的','耍酷的','酷炫的',
            '神勇的','年轻的','唠叨的','瘦瘦的','无情的','包容的','顺心的','畅快的','舒适的','靓丽的',
            '负责的','背后的','简单的','谦让的','彩色的','缥缈的','欢呼的','生动的','复杂的','慈祥的',
            '仁爱的','魔幻的','虚幻的','淡然的','受伤的','雪白的','高高的','糟糕的','顺利的','闪闪的',
            '羞涩的','缓慢的','迅速的','优秀的','聪明的','含糊的','俏皮的','淡淡的','坚强的','平淡的',
            '欣喜的','能干的','灵巧的','友好的','机智的','机灵的','正直的','谨慎的','俭朴的','殷勤的',
            '虚心的','辛勤的','自觉的','无私的','无限的','踏实的','老实的','现实的','可靠的','务实的',
            '拼搏的','个性的','粗犷的','活力的','成就的','勤劳的','单纯的','落寞的','朴素的','悲凉的',
            '忧心的','洁净的','清秀的','自由的','小巧的','单薄的','贪玩的','刻苦的','干净的','壮观的',
            '和谐的','文静的','调皮的','害羞的','安详的','自信的','端庄的','坚定的','美满的','舒心的',
            '温暖的','专注的','勤恳的','美丽的','腼腆的','优美的','甜美的','甜蜜的','整齐的','动人的',
            '典雅的','尊敬的','舒服的','妩媚的','秀丽的','喜悦的','甜美的','彪壮的','强健的','大方的',
            '俊秀的','聪慧的','迷人的','陶醉的','悦耳的','动听的','明亮的','结实的','魁梧的','标致的',
            '清脆的','敏感的','光亮的','大气的','老迟到的','知性的','冷傲的','呆萌的','野性的','隐形的',
            '笑点低的','微笑的','笨笨的','难过的','沉静的','火星上的','失眠的','安静的','纯情的','要减肥的',
            '迷路的','烂漫的','哭泣的','贤惠的','苗条的','温婉的','发嗲的','会撒娇的','贪玩的','执着的',
            '眯眯眼的','花痴的','想人陪的','眼睛大的','高贵的','傲娇的','心灵美的','爱撒娇的','细腻的',
            '天真的','怕黑的','感性的','飘逸的','怕孤独的','忐忑的','高挑的','傻傻的','冷艳的','爱听歌的',
            '还单身的','怕孤单的','懵懂的'];

        $nicheng_wei = [
            '嚓茶','凉面','便当','毛豆','花生','可乐','灯泡','哈密瓜','野狼','背包','眼神','缘分','雪碧',
            '人生','牛排','蚂蚁','飞鸟','灰狼','斑马','汉堡','悟空','巨人','绿茶','自行车','保温杯','大碗',
            '墨镜','魔镜','煎饼','月饼','月亮','星星','芝麻','啤酒','玫瑰','大叔','小伙','哈密瓜，数据线',
            '太阳','树叶','芹菜','黄蜂','蜜粉','蜜蜂','信封','西装','外套','裙子','大象','猫咪','母鸡',
            '路灯','蓝天','白云','星月','彩虹','微笑','摩托','板栗','高山','大地','大树','电灯胆','砖头',
            '楼房','水池','鸡翅','蜻蜓','红牛','咖啡','机器猫','枕头','大船','诺言','钢笔','刺猬','天空',
            '飞机','大炮','冬天','洋葱','春天','夏天','秋天','冬日','航空','毛衣','豌豆','黑米','玉米',
            '眼睛','老鼠','白羊','帅哥','美女','季节','鲜花','服饰','裙子','白开水','秀发','大山','火车',
            '汽车','歌曲','舞蹈','老师','导师','方盒','大米','麦片','水杯','水壶','手套','鞋子','自行车',
            '鼠标','手机','电脑','书本','奇迹','身影','香烟','夕阳','台灯','宝贝','未来','皮带','钥匙',
            '心锁','故事','花瓣','滑板','画笔','画板','学姐','店员','电源','饼干','宝马','过客','大白',
            '时光','石头','钻石','河马','犀牛','西牛','绿草','抽屉','柜子','往事','寒风','路人','橘子',
            '耳机','鸵鸟','朋友','苗条','铅笔','钢笔','硬币','热狗','大侠','御姐','萝莉','毛巾','期待',
            '盼望','白昼','黑夜','大门','黑裤','钢铁侠','哑铃','板凳','枫叶','荷花','乌龟','仙人掌','衬衫',
            '大神','草丛','早晨','心情','茉莉','流沙','蜗牛','战斗机','冥王星','猎豹','棒球','篮球','乐曲',
            '电话','网络','世界','中心','鱼','鸡','狗','老虎','鸭子','雨','羽毛','翅膀','外套','火','丝袜',
            '书包','钢笔','冷风','八宝粥','烤鸡','大雁','音响','招牌','胡萝卜','冰棍','帽子','菠萝','蛋挞',
            '香水','泥猴桃','吐司','溪流','黄豆','樱桃','小鸽子','小蝴蝶','爆米花','花卷','小鸭子','小海豚',
            '日记本','小熊猫','小懒猪','小懒虫','荔枝','镜子','曲奇','金针菇','小松鼠','小虾米','酒窝','紫菜',
            '金鱼','柚子','果汁','百褶裙','项链','帆布鞋','火龙果','奇异果','煎蛋','唇彩','小土豆','高跟鞋',
            '戒指','雪糕','睫毛','铃铛','手链','香氛','红酒','月光','酸奶','银耳汤','咖啡豆','小蜜蜂','小蚂蚁',
            '蜡烛','棉花糖','向日葵','水蜜桃','小蝴蝶','小刺猬','小丸子','指甲油','康乃馨','糖豆','薯片','口红',
            '超短裙','乌冬面','冰淇淋','棒棒糖','长颈鹿','豆芽','发箍','发卡','发夹','发带','铃铛','小馒头',
            '小笼包','小甜瓜','冬瓜','香菇','小兔子','含羞草','短靴','睫毛膏','小蘑菇','跳跳糖','小白菜','草莓',
            '柠檬','月饼','百合','纸鹤','小天鹅','云朵','芒果','面包','海燕','小猫咪','龙猫','唇膏','鞋垫',
            '羊','黑猫','白猫','万宝路','金毛','山水','音响'];

        $tou_num=mt_rand(0,331);

        $wei_num=mt_rand(0,325);

        $nicheng=$nicheng_tou[$tou_num].$nicheng_wei[$wei_num];

        return $nicheng; //输出生成的昵称
    }
    # endregion

}